C programs to calculate the sum and the average of N numbers have been shown here. For example, if the numbers are 10, 20, 30, 40, 50, then the sum of these numbers would be 10 + 20 + 30 + 40 + 50 = 150 and average would be (150 / 5) = 30. The result can be obtained using array and also without using array.
Page Contents:
1. Algorithm to find the sum and average of N numbers
1. Take number of terms $n$ as inputs.
2. Set $s = 0$ and $i = 0$
3. Take a number $x$ as input.
4. Perform $s = s + x$ and $i = i + 1$
5. Check if $i < n$, then go to step 3, else go to step 6
6. Display $s$ as the sum and $\frac{s}{n}$ as the average and exit program.
2. Pseudocode to find the sum and average of N numbers
Input: Number of terms $n$
Output: Sum and average of those $n$ terms
1. Procedure sumAverage($n$):
2.
3.
4.
5.
6.
7.
8.
9.
10. End Procedure
3. Time complexity to find the sum and average of N numbers
Time Complexity: O(n)
Here $n$ is the number of elements.
4. C Program & output to calculate sum & average of n numbers without array
/*********************************** alphabetacoder.com C Program to calculate sum and average of n numbers without array ************************************/ #include<stdio.h> int main() { // delclare variables int i, n, num, sum = 0; float avg; // take input of number of elements printf("Enter no of elements: "); scanf("%d", & n); // take input of numbers one by one // add each number to sum printf("Enter %d elements: \n", n); for (i = 1; i <= n; i++) { scanf("%d", & num); sum = sum + num; } // calculate average avg = (float) sum / n; // display result printf("Sum: %d\n", sum); printf("Average: %f\n", avg); return 0; }
Output
Enter no of elements: 6
Enter 6 elements:
4
6
1
5
10
4
Sum: 30
Average: 5.000000
5. C Program to calculate sum & average of n numbers using array
/******************************* alphabetacoder.com C Program to calculate sum and average of n numbers using array *********************************/ #include<stdio.h> int main() { // delclare variables int i, n, N[20] = {0}, sum = 0; float avg; // take input of number of elements printf("Enter no of elements: "); scanf("%d", & n); // take input and store into array printf("Enter %d elements: \n", n); for (i = 0; i < n; i++) { scanf("%d", & N[i]); } // perform sum of array elements for (i = 0; i < n; i++) { sum = sum + N[i]; } // calculate average avg = (float) sum / n; // display result printf("Sum: %d\n", sum); printf("Average: %f\n", avg); return 0; }
Output
Enter no of elements: 7
Enter 7 elements:
4
9
1
10
11
9
3
Sum: 47
Average: 6.714286