Skip to main content

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 until break is executed on reading 0.
  • count keeps the number of values, and the check count > 0 prevents division by zero.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →