w3resource

C Exercises: Calculate and print the average of some integers


Calculate the average of integers until 888 is entered

Write a C program to calculate and print the average of some integers. Accept all the values preceding 888.

Sample Input: 12
15
24
888

Sample Solution:

C Code:

#include <stdio.h>

int main()
{
int ctr = 0, n;       // Initialize counter and variable for input
int sum = 0;          // Initialize sum variable
float avg_value = 0;  // Initialize average variable

    // Prompt user for input
printf("Input each number on a separate line (888 to exit):\n");

    // Read the first number
scanf("%d", &n);

    // Loop until the user enters 888
while (n != 888) {
sum += n;  // Add the number to the sum
ctr++;     // Increment counter
scanf("%d", &n); // Read the next number
    }

    // Calculate the average if there were inputs
if (ctr)
avg_value = (float) sum / ctr;

    // Print the average value
printf("\nThe average value of the said numbers is %f\n", avg_value);

return 0; // Indicate successful execution of the program
}

Sample Output:

Input each number on a separate line (888 to exit):

The average value of the said numbers is 17.000000

Flowchart:

C Programming Flowchart: Calculate and print the average of some integers.


For more Practice: Solve these Related Problems:

  • Write a C program to compute the average of integers entered by the user, terminating when 888 is input.
  • Write a C program to calculate the average of positive integers until a sentinel value of 888 is encountered.
  • Write a C program to continuously read integers and calculate the running average until 888 is entered.
  • Write a C program to compute the average of user-input numbers and handle the termination condition of 888 gracefully.

Go to:


PREV :Count occurrences of the digit 3 in a number.
NEXT : Print Roman numeral equivalents for numbers 1 to 50.

C programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.