Calculate the Average of Given Numbers in C


Calculating the average of a set of numbers is a fundamental mathematical operation used in a wide range of applications. In programming, it is often necessary to calculate the average of a set of values, such as grades, test scores, or user ratings. In this blog post, we will discuss how to calculate the average of given numbers using a for loop in the C programming language.


int main(void)

    int n,newn,sum=0;
    float avg;

    printf("Enter the number %d: ", i);
    scanf("%d", &n);


    for(int i=1; i<=n; i++)
        printf("Enter the number i: ");
        scanf("%d", &newn);
        avg= sum/n;


    printf("\nAverage:%f\n", avg);
    return 0;

First, we define the variables needed to store the user input values, the sum of those values, and the average. We then ask the user how many numbers they want to enter and store the value in the n variable.

Next, we use a for loop to iterate through the user input values. In each iteration, we ask the user to enter a number and store it in the newn variable. We then add this value to the sum variable, which keeps track of the total sum of the user input values. After each iteration, we calculate the current average by dividing the sum by the number of values entered so far in variable n, and store the result in the avg variable.

Finally, when the loop completes, we print the average to the console using the printf() function.


How many numbers you want to enter? 5

Enter the number 1: 7
Enter the number 2: 2
Enter the number 3: 9
Enter the number 4: 1
Enter the number 5: 3



Please enter your comment!
Please enter your name here