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     

No comments:

Post a Comment