C programs to find the sum and average of the numbers until 0 is entered, are given here. Suppose the input numbers are 5, 10, 9, 0, then the sum = (5 + 10 + 9) = 24 and average = (5 + 10 + 9) / 3 = 8.
Page content(s):
1. Algorithm to find the sum and average of the numbers until 0 is entered
1. Set sum = 0, count = 0.
2. Take a number n as input.
3. Perform sum = sum + n.
4. Check if n = 0
5. If step 4 is true declare sum and as the sum and (sum / count) as the average of the numbers entered.
6. If step 4 is false, perform count = count + 1 and go to step 2
2. Pseudocode to find the sum and average of the numbers until 0 is entered
1. Procedure sumAverage():
2.
3.
4.
5.
6.
7.
8.
9.
10.
11. End Procedure
3. Time complexity to find the sum and average of the numbers until 0 is entered
Time Complexity: O(n)
Here n is the number of terms.
4. Program to find the sum and average of the numbers until 0 is entered
4.1. C Program to find the sum and average of the numbers until 0 is entered using iteration
/******************************** alphabetacoder.com C program to find average and sum of numbers until 0 is entered *********************************/ #include <stdio.h> int main() { // declare variables int n, count, sum; // initialize sum = 0; count = -1; // keep taking input // until 0 is entered do { // take input printf("Enter a number: "); scanf("%d", & n); // add to sum sum = sum + n; // increment the value of number count count++; } while (n != 0); // display the sum and average printf("\nTotal number entered: %d\n", count); printf("Sum: %d\n", sum); printf("Average: %lf\n", (double) sum / count); return 0; }
Output
Enter a number: 8
Enter a number: 3
Enter a number: 5
Enter a number: -4
Enter a number: 3
Enter a number: 1
Enter a number: 0
Total number entered: 6
Sum: 16
Average: 2.666667
4.2. C Program to find the sum and average of the numbers until 0 is entered using recursion
/******************************************* alphabetacoder.com C program to find sum and average of numbers until 0 is entered using recursion ********************************************/ #include <stdio.h> void findSumAverage(int sum, int count) { // take input int n; printf("Enter a number: "); scanf("%d", & n); // keep taking input // until 0 is entered if (n == 0) { printf("\nTotal numbers entered: %d\n", count); printf("Sum: %d\n", sum); printf("Average: %lf\n", (double) sum / count); } else { // add input to sum and increment count sum += n; count++; findSumAverage(sum, count); // recursive call } } int main() { // declare and initialize variables int sum = 0, count = 0; // call function to display result findSumAverage(sum, count); return 0; }
Output
Enter a number: 1
Enter a number: 3
Enter a number: 5
Enter a number: 0
Total number entered: 3
Sum: 9
Average: 3.000000