Sunday, December 22, 2013

Chapter 6: ARRAYS



6.1 Introduction and Declaration of Array

What is array?

An array is a collection of identical data objects, which are stored in the consecutive memory locations under a common heading or a variable name. In other word, array is a group or a table of value referred to by the same variable name. The individual values in an array are called elements.

Arrays are set of values of the same type, which have single name followed by an index. In C & C++, square brackets around the right after the name, with the first element referred to by the number. Whenever a variable name with an index appears in an expression, C & C++ compiler assumes that element to be an array type.

Array declaration

Declaring the name and type of an array and setting the number of element in an array is known as dimensioning the array. It must be declared before one uses it in a C program like other variables. In the array declaration, one must define the type of array, Name of the array and the total number of memory locations to be allowed.

In general, one-dimensional array may be expressed as
For example:
     int marks [300];

6.2 One dimensional and Multidimensional Array

One Dimensional Array

The automatic arrays cannot be initialized, unlike automatic variables. However, external and static arrays can be initialized if it is desired. The initial values must appear in the same order in which they will be assigned to the individual array elements, enclosed in braces and separated by commas.
The general format of the array initialization is,
datatype array_name [expression] = {element1, element2… element n}
For example
int values[3]={10,11,12}
char sex [2] = {‘m’,’f ‘}
float co_ordinates [4] = {0, 0.45,-0.50,-4.0}
The results of each of the value of array element are;
values [0] =10
values [1] =11
values [2] =12
sex [0] = ‘m’
sex [1] = ‘f ‘

co_ordinates [0] = 0
co_ordinates [1] =0.45
co_ordinates [2] = -0.50
co_ordinates [3] = -4.0

Note that in C & C++, the first element is always placed in 0th  place; it means that array
Starts from 0 to n-1. Where n is the maximum size of the array declared by the
programmer.

Example                     
A program to initialize a set of numbers the array and to display it in standard output.
                                                                                           
11
12
13
14
15
16
main()

int a [7] = {11,12,13,14,15,16,17};                     
            int i;                                                                
printf(“contents of the array \n”);
            for(i =0; i<=6; ++i)
                        printf(“%d\t”,a[i]);
            getch( );  
}

Sorting           
Arranging data either in increasing or decreasing order is called sorting. Here we will discuss about two types of sorting techniques:
i. Bubble sort   
ii. Selection sort

Bubble Sort
The basic idea of bubble sort is to compare two neighboring objects, and to swap them if they are in the wrong order.
Bubble sort focuses on successive adjacent pairs of elements in the array, compares them, and either swaps them or not. In either case, after such a step, the larger of the two elements will be in the higher index position. The focus then moves to the next higher position, and the process is repeated. When the focus reaches the end of the effective array, the largest element will have ``bubbled'' from whatever its original position to the highest index position in the effective array.
For example, consider the array:
45, 67, 12, 34, 25, 39,
In the first step, the focus is on the first two elements which are compared and swapped, if necessary. In this case, since the element at index 1 is larger than the one at index 0, no swap takes place.
45, 67, 12, 34, 25, 39
Then the focus move to the elements at index 1 and 2 which are compared and swapped, if necessary. In our example, 67 is larger than 12 so the two elements are swapped. The result is that the largest of the first three elements is now at index 2.
45, 12, 67, 34, 25, 39
The process is repeated until the focus moves to the end of the array, at which point the largest of all the elements ends up at the highest possible index. The remaining steps and result are:
45, 12, 34, 67, 25, 39
45, 12, 34, 25, 67, 39
45, 12, 34, 25, 39, 67
Thus, in first pass the largest element has bubbled to the top index of the array.The process is repeated again and again to sort an entire array.
Given an array a of numbers, with length n, here's a snippet of C code for bubble sort (Descending Sort):
for (i=0; i<n-1; i++) 
{
  for (j=0; j<n-1-i; j++)
    if (a[j+1] < a[j])   /* compare the two neighbors */
     {tmp = a[j];         /* swap a[j] and a[j+1]      */
      a[j] = a[j+1];
      a[j+1] = tmp;
     }
}
As we can see, the algorithm consists of two nested loops. The index j in the inner loop travels up the array, comparing adjacent entries in the array (at j and j+1), while the outer loop causes the inner loop to make repeated passes through the array. After the first pass, the largest element is guaranteed to be at the end of the array, after the second pass, the second largest element is in position, and so on. That is why the upper bound in the inner loop (n-1-i) decreases with each pass: we don't have to re-visit the end of the array.
In bubble sort if there are n elements to be sorted it will take n-1 pass to sort entire elements.

Selection Sort
The idea of selection sort is rather simple: we repeatedly find the next largest (or smallest) element in the array and move it to its final position in the sorted array. Assume that we wish to sort the array in increasing order, i.e. the smallest element at the beginning of the array and the largest element at the end. We begin by selecting the largest element and moving it to the highest index position. We can do this by swapping the element at the highest index and the largest element. We then reduce the effective size of the array by one element and repeat the process on the smaller (sub)array. The process stops when the effective size of the array becomes 1 (an array of 1 element is already sorted).
For example, consider the following array, shown with array elements in sequence separated by commas:
63, 75, 90, 12, 27
The leftmost element is at index zero, and the rightmost element is at the highest array index, in our case, 4 (the effective size of our array is 5). The largest element in this effective array (index 0-4) is at index 2. We have shown the largest element and the one at the highest index in bold. We then swap the element at index 2 with that at index 4. The result is:
63, 75, 27, 12, 90
We reduce the effective size of the array to 4, making the highest index in the effective array now 3. The largest element in this effective array (index 0-3) is at index 1, so we swap elements at index 1 and 3 (in bold):
63, 12, 27, 75, 90
The next two steps give us:

27, 12, 63, 75, 90
12, 27, 63,75, 90

The last effective array has only one element and needs no sorting. The entire array is now sorted.
Given an array a of numbers, with length n, here's a snippet of C code for selection sort:
for (i=0; i<n-1; i++) 
{
  for (j=i+1; j<n; j++)
    if (a[i] < a[j])   
     {tmp = a[i];         
      a[i] = a[j];
      a[j] = tmp;
     }
}
 

Multidimensional Array

Multidimensional arrays are similar to single dimensional array expect two separate pair of square brackets is required. Similarly three dimensional arrays require three pair of square brackets and so on.
In general two dimensional arrays may be expressed as:
data type   array name [expression 1] [expression 2];
For example
int x[2][2]={1,2,3,4}

Where x is the two dimensional array of integer numbers whose maximum size is 4 and the assignments would be
x [0] [0] =1
x [0] [1] =2
x [1] [0] =3
x [1] [1] =4
float sum[3] [2] = {0.1,0.2,0.3,0.4,0.5,0.6}
Where value is a two dimensional array of integer numbers whose maximum size is 6 and the assignment would be
sum [0] [0] = 0.1          sum [1] [0] =0.3          sum [2] [0] =0.5
sum [0] [1] =0.2           sum [1] [1] =0.4           sum [2] [1] = 0.6

eg. int values[3][2]={{10,21},{3,45},{52,-6}}

10
21
3
45
52
-6
Example
A program to initialized a set of numbers in two dimensional array a and to display the content of the array on screen.
#include<stdio.h>
#include <conio.h>
 main ( )
{
            int i,j;
            float a [3] [4] = {
                                       {1,2,3,4},
                                        {5,6,7,8},
                                        {9,10,11,12},
                                    };

printf(“values in the array\n”);
for (i=0;i<3:i++)
{
                        for (j=0;j<4;j++)
printf("%d\t”,a[i][j]);
}
}



6.3 Character Array and String Manipulation (String Declaration)
The string that will hold an array of character which is declared in the format
Storage class character data type array _name [size];
e.g. char name[10];
So here, the declaration char name [10] declares the name as the character array (string) variable that can hold a maximum of character. Suppose user want to store constant string “program” into char array name.
Here each element is treated as an element of the array name and stored in the memory as follows

   0              1            2             3            4            5             6            7         8              9
P
R
O
G
R
A
M
\0

                                                                                                                  null character
                                                                                                               
When the compiler encounters a constant string, it terminates with an additional null character. So while declaring character arrays, we must always reserve one extra element space for the terminator.

Initializing a string

A string cannot be initialized like other variables. The following way of declaring a string is not possible.
char name [16];
name [16]= “programming”;
The general rule is that each element of an array_each character of a string is a separate variable. There we should initialize each character in a string should be initialized individually, as we always do while initializing an array.
Same string can be initialized as follows
name[0]= “p”
name[1]= “r”
name[2]= 'o’
name[3]= 'g'
name[4] = 'r'
name[5]= 'a'
name[6]= 'm'
name[7]= 'm'
name[8]= 'e'
Similarly same string can be initialized in other array
char name []={‘p’ ,‘r’,’o’,’g’,’r’,’a’,’m’,’m’,’e’};

String functions


String Concatenation:
The function strcat(string1, string2); concatenates the character string 1 and string2 to the end of the string1, placing a null character at the end of the final string. Finally function returns string1.

Example

Program to concatenate two strings.
#include<stdio.h>
#include<string.h>
main ( )
{
            char string1[ ]=”spot”;
            char string2 [ ]= “light”;
            strcat (string1, string2);
            printf("%s",string1);
getch( );
}

String Compare:

strcmp(string1,string2) compares two strings and return 1 if they are different and 0 if they are similar.


Example

Program to compare two strings.
#include<stdio.h>
#include<string.h>
main( )
{
            char string1[10],string2[10];
            int a;
printf(“enter a word:”);
            scanf("%s",string1);
            printf(“Enter another word for comparision”);
            scanf("%s",string2);
            a=strcmp (string1,string2);
            if (a= =0)
                        printf(“They are similar words \n”);
            else
                        printf(“They are not similar words \n”);
getch( );
}

String Copy
The function strcpy(string1, string2); copy the character string2 to string1 and finally function returns string1.

Example:

Program to copy a string to another string.
#include<stdio.h>
#include<conio.h>
 main ( )
{
            char string1[15], string2[10];
            printf("Enter the first word \n”);
scanf("%s",string1);
printf("Enter the word to be copied”);
scanf("%s",string2);
strcpy(string1,string2);
printf("%s",string1);
}

String Length:
Strlen(string) returns the number of character in string, excluding the null characters.

Example:

Program to compare the length of two string.
#include<stdio.h>
#include <conio.h>
main( )
{
            int n1,n2;
            char str[15], str[15];
            printf(“Enter two words”);
            scanf("%s %s",str,str1);
n1=strlen(str);
n2=strlen(str1);
if (n1= =n2)
printf("they are of equal size \n”);
else
printf(”they are not equal \n”);
}

String Lower and Upper
Strlwr(string) converts entire string to lowercase and strupr(string) converts wntire string to uppercase.

 

Example:


Program to convert a string from lowercase to uppercase and from uppercase to lowercase.
#include<stdio.h>
#include<conio.h>
 main ( )
{
            char string1[15], string2[10];
            printf("Enter the string inuppercase \n”);
scanf("%s",string1);
printf("Enter the string in lowercase”);
scanf("%s",string2);
strlwr(string1);
printf("%s",string1);
strupr(string2);
printf("%s",string2);
}
    

bubble sort ascending
#include<stdio.h>
#include<conio.h>
main()
{
int a[10];
int i,j;
int n,temp;
printf("how many nos:");
scanf("%d",&n);
for(i=0;i<n;i++)
            scanf("%d",&a[i]);
printf("\n\n Content\n");
for(i=0;i<n;i++)
            printf("%d\t",a[i]);

for (i=0; i<n-1; i++)
{
  for (j=0;j<n-1-i;j++)
    if (a[j] > a[j+1])   /* compare the two neighbors */
     {temp = a[j];         /* swap a[j] and a[j+1]      */
      a[j] = a[j+1];
      a[j+1] = temp;
     }
}
printf("\n");
 for(i=0;i<n;i++)
            printf("%d\t",a[i]);
 getch();
 }

End of Chapter Six
[ Note: If you have any problems regarding this then you can post the problem in comment box. we will try to solve this here. Or if you know any solution, you can also help :) ]

No comments:

Post a Comment