C program to calculate sum and average of an array/
C program to calculate sum and average of an array
This C program finds the sum and average of an array. First it asks the user to input the desired number of elements in the array. Then, it ask the user to input each element of the array and display the sum and average of entered elements.
C program to calculate sum and average of an array - Source code
int n, i, sum = 0;
printf("Enter the number of elements you want in Array : ");
for (i = 0; i < n; i++)
printf("Enter element %d : ", i + 1);
sum = sum + Arr[i];
average = (float)sum/n;
printf("\nThe sum of the elements array is : %d", sum);
printf("\nThe average of the elements array is : %0.2f", average);
Enter the number of elements you want in Array : 6
Enter element 1 : 23
Enter element 2 : 54
Enter element 3 : 69
Enter element 4 : 25
Enter element 5 : 12
Enter element 6 : 5
The sum of the elements array is : 188
The average of the elements array is : 31.33
1. First the program user is asked to enter the value of n, which is the desired number of elements in the array.
2. Then each number is saved in array using a scanf statement inside a for loop. Note that the sum of array is also calculated in the same for loop.
3. To calculate the average of the array, (sum/no of elements) mathematical formula is used. Here important thing to note that is sum variable is type casted to float type in order to print the average as float.
4. At last, both sum and average are displayed as output of the program.
Install Computer Science Bits Android app to access all study material on the go.