Translate

Labels

Thursday 4 April 2013

PROCESSING ONE DIMENSIONAL ARRAY

TO ACCEPT A LIST OF NUMBERS INTO A 1-d ARRAY, FIND THEIR SUM, AVERAGE AND DISPLAY THEM.

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n, sum;
float avg;
clrscr();
printf("Enter no.of elements [1-10]\n");
scanf("%d",&n);
printf("Enter %d numbers \n ",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("The number are \n");
for(i=0;i<n;i++)
printf("%4d",a[i]);
/*Finding the sum and average begins*/
sum=0;
for(i=0;i<n;i++)
sum+=a[i];
avg=(float)sum/n;
/*Finding the sum and average ends*/
printf("\n Sum=%d\n",sum);
printf("\n Average=%f\n",avg);
getch();
}
OUTPUT
Enter no.of elements[1-10]
5
Enter 5 numbers
1   2   3   4   5
The numbers are
1   2   3   4   5
Sum=15
Average=3.000000
Explanation
a is declared to be an array of int type and of size 10.Maximum 10 numbers can be written into the array.n,i and sum are declared to be variable of int type.n is to collect the number of values to be read into the array a,which lies within 1 and 10.i is to traverse all values in a sum is to collect the sum of the values in a avg is declared to be a variable of float type and it is to collect the average of values in a.
In the process of finding the sum of all the values initially sum is set to 0.A for loop is used select each number in the array and it added to sum with the statement.
sum+=a[i]
The statement
avg=(float)sum/n;
on its execution assign average value to avg. Note that we have used type casting to convert sum forcibly to float to get the exact result.Otherwise the expression (sum/n) produces only integral part of the quotient since both sum and n are integers.Both sum and avg are then displayed 

No comments: