C Program to Calculate Average
Here’s a C program that calculates the average of a list of numbers entered through the keyboard
#include
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

Explanation:
- The program begins by including the necessary header file
stdio.h
, which allows us to use input/output functions such asprintf
andscanf
. - 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, andaverage
to store the calculated average. - We prompt the user to enter the number of elements they wish to enter, using the
printf
function. - We use the
scanf
function to read the value entered by the user and store it in thecount
variable. - We display a prompt asking the user to enter the numbers.
- Using a
for
loop, we iteratecount
number of times and within each iteration, we usescanf
to read a number from the user and add it to thesum
variable. - After the loop finishes, we calculate the average by dividing the
sum
by thecount
of elements. - 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.