- 2068 Shrawan · 8 marks
Sum and average until 0 is entered
Short answer
Read numbers in a loop, summing and counting until 0 is entered; then if count > 0 compute average = sum/count and display both with two decimals. Zero is not included.
Write a program to read values from user and find sum until user types 0, also display sum and average.
The program reads numbers in a loop, adds each to sum and counts them, and stops when 0 is entered. The average is sum / count. If 0 is typed first (no data), a message is displayed to avoid division by zero. The zero itself is not included in the sum or the count.
#include <stdio.h>
int main(void)
{
float num, sum = 0, avg;
int count = 0;
printf("Enter numbers (0 to stop):\n");
while (1)
{
scanf("%f", &num);
if (num == 0)
break;
sum += num;
count++;
}
if (count > 0)
{
avg = sum / count;
printf("Sum = %.2f\nAverage = %.2f\n", sum, avg);
}
else
printf("No numbers were entered.\n");
return 0;
}
Output for the input 4, 7, 10, 3.5, 0:
Enter numbers (0 to stop):
Sum = 24.50
Average = 6.12
Here the sum is 24.5 for 4 numbers, so the average is 6.125. With gcc (glibc), %.2f prints this as 6.12, because 6.125 is stored exactly and the tie is rounded to even; some other compilers print 6.13.
Explanation
while (1)loops untilbreakis executed on reading 0.countkeeps the number of values, and the checkcount > 0prevents division by zero.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Read records until end; show nth record · Computer Programming, chapter 10 · asked 2×
- Sum of digits until single digit · Computer Programming, chapter 5 · asked 2×
- GOTO types; sum of series program · Computer Programming, chapter 11
- Sum and average between M and N using pointer · Computer Programming, chapter 9
- Count even and odd until -1 · Computer Programming, chapter 5
- Count prime and composite until -1 · Computer Programming, chapter 5
- Function template: sum and average of array · Object Oriented Programming, chapter 9
- C program: sum of two 8-bit BCD numbers · Embedded System, chapter 9
- Function overloading; new/delete average program · Object Oriented Programming, chapter 3
- 8086 ALP: display only alphabetic characters · Microprocessor, chapter 3