C Program to Calculate Average

Here’s a C program that calculates the average of a list of numbers entered through the keyboard

				
					#include <stdio.h>

int main() {
  int count, i;
  float number, sum = 0, average;

  printf("Enter the number of elements: ");
  scanf("%d", & count);

  printf("Enter %d numbers:\n", count);

  // Read numbers from the user and calculate the sum
  for (i = 0; i < count; i++) {
    scanf("%f", & number);
    sum += number;
  }

  // Calculate the average
  average = sum / count;

  // Display the average
  printf("The average is: %.2f\n", average);

  return 0;
}
				
			
Output
C program to find average of list of numbers entered through keyboard

Explanation:

  1. The program begins by including the necessary header file stdio.h, which allows us to use input/output functions such as printf and scanf.
  2. We declare the necessary variables: count to store the number of elements, i as a loop counter, number to store each number entered by the user, sum to accumulate the sum of the numbers, and average to store the calculated average.
  3. We prompt the user to enter the number of elements they wish to enter, using the printf function.
  4. We use the scanf function to read the value entered by the user and store it in the count variable.
  5. We display a prompt asking the user to enter the numbers.
  6. Using a for loop, we iterate count number of times and within each iteration, we use scanf to read a number from the user and add it to the sum variable.
  7. After the loop finishes, we calculate the average by dividing the sum by the count of elements.
  8. Finally, we display the calculated average using printf with the format specifier %.2f to display the average with two decimal places.

When you run the program, it will prompt you to enter the number of elements and then ask you to enter the numbers one by one. After you have entered all the numbers, it will calculate the average and display it on the screen.