Introduction
Handling dynamic input from users is a common requirement in C programming. In this tutorial, we will write a C program to find the sum and average of different numbers, where the user decides how many numbers to enter. This type of logic is useful in programs that don’t limit the user with a fixed number of entries and rely on loops for continuous input.
Problem Statement
Write a C program that keeps accepting numbers from the user until they want to stop. Once the input is done, the program should calculate and display the sum and average of all entered numbers.
C Program to Find Sum and Average of User Input
#include <stdio.h>
int main() {
int number, count = 0;
float sum = 0, average;
char choice;
do {
printf("Enter a number: ");
scanf("%d", &number);
sum += number;
count++;
printf("Do you want to enter another number? (y/n): ");
scanf(" %c", &choice); // space before %c to consume newline
} while(choice == 'y' || choice == 'Y');
if (count != 0) {
average = sum / count;
printf("Sum = %.2f\n", sum);
printf("Average = %.2f\n", average);
} else {
printf("No numbers were entered.\n");
}
return 0;
}
How the Code Works
- Input Loop: The
do-while
loop continues to take numbers until the user enters ‘n’ or ‘N’. - Sum Calculation: Each new number is added to
sum
, andcount
keeps track of the total entries. - Average: Once input ends, average is calculated as
sum / count
.
Sample Output
Enter a number: 10
Do you want to enter another number? (y/n): y
Enter a number: 20
Do you want to enter another number? (y/n): y
Enter a number: 30
Do you want to enter another number? (y/n): n
Sum = 60.00
Average = 20.00
Why This Program is Useful
- Great for practice with loops and user input handling
- Demonstrates dynamic input
- Prepares you for tasks like working with lists, arrays, and calculating statistics
Conclusion
This C program to find the sum and average of user input offers a flexible way to accept any number of inputs and is a great way to build confidence with loops, input/output, and conditional logic in C. It’s a basic yet essential concept every beginner should practice.