Showing posts with label 7. ARRAYS. Show all posts
Showing posts with label 7. ARRAYS. Show all posts

Sunday, December 27, 2009

7.5 ARRAYS AND STRINGS

Most C compilers include library functions that allow strings to be compared, copied or concatenated (i.e combined, one behind another).Other library functions permit operations on individual characters within strings; e.g., they allow individual characters to be located within strings, and so on.The following example illustrates the use of some of these library functions.

/* sort a list of strings alphabetically using a two-dimensional character array*/


#include < stdio.h >
#include < stdlib.h >
#include < string.h >


void reorder (int n, char x[][12]);  /* function prototype*/


main()
{
int i, n = 0;
char x[10][12];


printf ("Enter each string on a separate line below\n\n");
printf ("Type \ 'END\ ' when finished\n\n");


/*read in the list of strings*/
do  {
printf ("string %d: ", n+1);
scanf ("%s", x[n]);

} while (strcmp(x[n++], "END"));


/* adjust the value of n*/
n--;


/* reorder the list of strings*/
reorder(n, x);


/* display the reordered list of strings */
printf("\n\nReordered List of strings: \n");
for (i=0; i < n;++i)
printf("\nstring %d: %s", i+1, x[i]);
}


void reorder(int n, char x[][12])  /* rearrange the list of strings */
{
char temp[12];
int i, item ;




for (item=0; item <  n-1;++item)


/* find the lowest of all remaining strings */
for (i=item+1; i <  n;++i)


if (strcmp(x[item], x[i]) > 0)  {
/* interchange the two strings */
strcpy(temp, x[item]);
strcpy(x[item], x[i]);
strcpy(x[i], temp);


}
return;
}

The strcmp function appears in two different places within this program : in main, when testing for a stopping condition, and in rearrange, when testing for the need to interchange two strings.The actual string interchange is carried out using strcpy.The dialog resulting from a typical execution of the program is shown below.The user's response are underlined, as usual.

Enter each string on a separate line below

Type 'END ' when finished

string 1: PACIFIC
string 2: ATLANTIC
string 3: INDIAN
string 4: CARIBBEAN
string 5: BERING
string 6: BLACK
string 7: RED
string 8: NORTH
string 9: BALTIC
string 10: CASPIAN
string 11: END

Reordered List of strings:


string 1: ATLANTIC
string 2: BALTIC
string 3: BERING
string 4: BLACK
string 5: CARIBBEAN
string 6: CASPIAN
string 7: INDIAN
string 8: NORTH

string 9: PACIFIC
string 10: RED

Saturday, December 26, 2009

7.4 MULTIDIMENSIONAL ARRAYS

Multidimensional arrays are defined in much the same manner as one-dimensional arrays, except that a separate pair of square brackets is required for each subscript.Thus, a two dimensional array will require two pair of square brackets, a three-dimensional array will require three pair of square brackets, and so on.

In general terms a multidimensional array definition can be written as

storage-class data-type array[expression 1][expression 2].....[expression n] 

where  storage-class refers to the storage class of the array, data-type is its data type, array is the array name, and expression 1, expression 2,......,expression n are positive valued integer expressions that indicate the number of array elements associated with each subscript.Remember that the storage-class is optional ;the default values are automatic for arrays that are defined inside of  a function, and external for arrays defined outside of a function.

Consider the following two dimensional array definition.

int values[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};

Note that the value can be thought of a table having 3 rows and 4 columns (4 elements per row).Since initial values are assigned by rows (i.e. last subscript increasing most rapidly), the results of this initial assignments are as follows.

values[0][0] = 1  values[0][1] = 2   values[0][2] = 3   values[0][3] = 4
values[1][0] = 5  values[1][1] = 6   values[1][2] = 7   values[1][3] = 8  
values[2][0] = 9  values[2][1] = 10  values[2][2] = 11 values[2][3] = 12 


Remember the first subscript ranges from 0 to 2, and the second subscript ranges from 0 to 3.


Now consider the following three dimensional array definition.

int t[10][20][30] = {
                                  {             /*table 1*/
                                  {1, 2, 3, 4}, /*row 1*/
                                  {5, 6, 7, 8}, /*row 2*/
                                  {9, 10, 11, 12} /*row 3*/
                           },
                           {                  /*table 2*/
                                  {21, 22, 23, 24},  /*row 1*/
                                  {25, 26, 27, 28},  /*row 2*/
                                  {29, 30, 31, 32}  /*row 3*/ 
                            }
}

Think of this array as a collection of 10 tables, each having 20 rows and 30 columns.The groups of initial values will result in the assignment of the following  nonzero values in the first two tables.

t[0][0][0] = 1   t[0][0][1] = 2    t[0][0][2] = 3    t[0][0][3] = 4  
t[0][1][0] = 5   t[0][1][1] = 6    t[0][1][2] = 7    t[0][1][3] = 8  
t[0][2][0] = 9   t[0][2][1] = 10  t[0][2][2] = 11   t[0][2][3] = 12  


t[1][0][0] = 21   t[0][0][1] = 22    t[0][0][2] = 23   t[0][0][3] = 24  
t[1][1][0] = 25   t[0][1][1] = 26    t[0][1][2] = 27   t[0][1][3] = 28  
t[1][2][0] = 29   t[0][2][1] = 30    t[0][2][2] = 31   t[0][2][3] = 32  

All of the remaining array will be assigned zeros.

Friday, December 25, 2009

7.3 PASSING ARRAYS TO A FUNCTION

An entire array can be passed to a function as an argument.The manner in which the array is passed differs markedly, however, from that of an ordinary variable.

To pass an array to a function, the array name must appear by itself, without brackets or subscripts, as an actual argument within the function call.The corresponding formal argument is written in the same manner,though it must be declared as an array within the formal argument declarations.when declaring a one-dimensional array as a formal argument,the array name is written with a pair of empty square brackets.The size of the array is not specified within formal argument declaration.

Some care is required when writing function prototypes that include array arguments.An empty pair of square brackets must follow the name of each array argument, thus indicating that the argument is an array.If argument names are not included in a function declaration, then an empty pair of square brackets must follow the array argument data type.

When an array is passed to a function, however, the values of the array elements are not passed to the function.Rather, the array name is interpreted as the address of the first array element (i.e. the address of the memory location containing the first array element).This address is assigned to the corresponding formal argument when the function is called.Therefore the formal argument becomes a pointer to the first array element.Arguments that are passed in this manner are said to be passed by reference rather than by value.

Here is a simple C program that passes a three-element integer array to function, where the array elements are altered.The values of the array elements are displayed at three different places in the program, thus illustrating the effects of alterations.

 #include < stdio.h >


void modify (int a[]);    /*function prototype*/


main()
{
int count,a[3];     /*array definition*/


printf("\nFrom main, before calling the function: \n");
for (count=0; count <= 2; ++count)
{
a[count] = count + 1;
printf("a[%d] =\n", count, a[count]);
} 


modify(a);


printf("\nFrom main, after calling the function: \n");
for (count=0; count <= 2; ++count)
printf("a[%d] =\n", count, a[count]);


}


void modify (int a[])   /*Function definition*/

{
 int count;


printf("nFrom the function, after modifying the values: \n");
for (count=0; count <= 2; ++count) {
a[count] = -9;
printf("a[%d] =\n", count, a[count]);
}
return;

}

The array elements are assigned the values a[0] = 1, a[1] =2 and a[2] =3 within the first loop appearing in  main.These values are displayed as soon as they are assigned.The array is then passed to the function modify, when each array element is assigned the value -9.These new values are then displayed from within the function.Finally the values of the array elements are again displayed from main, after control has been transferred back to main from modify.

When the program is executed, the following output is generated.

From main, before calling the function:
a[0] = 1
a[1] =2 
a[2] =3

From the function, after modifying the values:
a[0] =-9
a[1] =-9
a[2] =-9

From main, after calling the function:

a[0] =-9
a[1] =-9
a[2] =-9

These results show that the elements of a are altered within main as a result of the changes that were made within modify. 

Tuesday, December 22, 2009

7.2 PROCESSING AN ARRAY

Single operations which involve entire arrays are not permitted in C.Thus, if a ans b are similar arrays (i.e. same data type, same dimensionality and same size), assignment operations, comparison operations, etc. must be carried out on an element-by-element basis.This is usually accomplished within a loop, where each pass through the loop is used to process one array element.The number of passes through the loop will therefore equal the number of array elements to be processed.

Let us write a C program that calculates the average of n numbers, then compute the deviation of each number about the average

#include < stdio.h>


main()
{
int n, count;
float avg, d, sum=0;
float list[100];


/*read a value for n*/


printf("\nHow many numbers will be averaged?");
scanf("%d", &n);
printf("\n");


/*read the numbers and calculate their sum*/


for (count=0;count < n;++count)   {
printf("i=%d x=  ", count+1);
scanf("%f", &list[count]);
sum +=list [count];

 

}



/*calculate and display the average*/
avg= sum / n;
printf("\nThe average is %5.2f\n\n", avg);



/*calculate and display the deviations about the average*/


for (count=0;count < n; ++count)   {
d= list[count] - avg;
printf("i=%d  x=%5.2f  d=%5.2f\n", count+1, list[count], d);



}

}

Now suppose the program is executed using the following five numerical quantities: x1=3, x2=-2, x3=12, x4=4.4, x5=3.5.The interactive session, including the data entry and the calculated results, is shown below. The user's response is underlined.

How many numbers will be averaged? 5
i=1  x=3
i=2  x=-2
i=3  x=12
i=4  x=4.4
i=5  x=3.5


The average is 4.18
i=1   x=  3.00    d=  -1.18   
i=2   x=  -2.00   d=  -6.18  
i=3   x=  12.00  d=  7.82

i=4   x=  4.40    d=  0.22
i=5   x=  3.50    d= -0.68     

Sunday, December 20, 2009

7.1 DEFINING AN ARRAY

Arrays are defined in much the same manner as ordinary variables, except that each array name must be accompanied by a size specification (i.e the number of elements).For a one-dimension array, the size is specified by a positive integer expression, enclosed in square brackets.The expression is usually written as a positive integer constatnt.

In general terms, a one-dimensional array definition may be expressed as

storage-class data-type array[ expression];

where storage-class refers to the storage class of the array,data-type is the data type, array is the array name, and expression is a positive-valued integer expression which indicates the number of array elements.The storage-class is optional;default values are automatic for arrays that are defined within a function or a block, and external for arrays that are defined outside of a function.

Several typical one-dimensional array definitions are shown below.

int x[100];
char text[80];
static char message[25];
static float n[12];

The first line states that x is a 100-element integer array, and the second defines text to be an 80-element character array.In the third line,message is defined as a static 25-element character array, whereas the fourth line establishes n as a static 12-element floating-point array.

Automatic arrays, unlike automatic variables, cannot be initialized.However, external and static array definitions can include the assignment of initial value if desired.The initial values must appear in the order in which they will be assigned to the individual array elements, enclosed in braces and separated by commas.The general form is

storage-class data-type array[expression]= {value1,value2,....,value n};

where value 1 refers to the value of the first array element,value 2 refers to the value of the second array element, and so on.The appearance of the expression, which indicates the number of array elements, is optional wen initial values are present.

Consider the following array definitions.

int digits[10] = {3, 3, 3};
static float x[6] = {-0.3, 0, 0.25};

The results, on an element-by-element basis, are as follows.

digits[0] = 3        x[0] =  -0.3
digits[1] = 3        x[1] =    0
digits[2] = 3        x[2] =   0.25
digits[3] = 0        x[3] =    0
digits[4] = 0        x[4] =    0
digits[5] = 0        x[5] =    0
digits[6] = 0       
digits[7] = 0      
digits[8] = 0      
digits[9] = 0       


In each case, all of the array elements are automatically set to zero except those that have been explicitly initialized within the array definitions.

The array size need not be specified explicitly when initial values are included as a part of an array definition.With a numerical array, the array size will automatically be set equal to the number of initial values included within the definition.

For example,
int digits[10] = {3, 3, 3};
static float x[6] = {-0.3, 0, 0.25}; can also be written as

int digits[ ] = {3, 3, 3};
static float x[ ] = {-0.3, 0, 0.25};