C Example for Beginners: C Program to Calculate Average Using Arrays

(C programming Example for Beginners)

C Program to Calculate Average Using Arrays

In this example, you will learn to calculate the average of n number of elements entered by the user using arrays.

Store Numbers and Calculate Average Using Arrays

#include <stdio.h>
int main(){
    int n, i;
    float num[100], sum = 0.0, avg;

    printf("Enter the numbers of elements: ");
    scanf("%d", &n);

    while (n > 100 || n < 1) {
        printf("Error! number should in range of (1 to 100).n");
        printf("Enter the number again: ");
        scanf("%d", &n);

    for (i = 0; i < n; ++i) {
        printf("%d. Enter number: ", i + 1);
        scanf("%f", &num[i]);
        sum += num[i];

    avg = sum / n;
    printf("Average = %.2f", avg);
    return 0;


Enter the numbers of elements: 6
1. Enter number: 45.3
2. Enter number: 67.5
3. Enter number: -45.6
4. Enter number: 20.34
5. Enter number: 33
6. Enter number: 45.6
Average = 27.69

Here, the user is first asked to enter the number of elements. This number is assigned to n.

If the user entered integer is greater less than 1 or greater than 100, the user is asked to enter the number again. This is done using a while loop.

Then, we have iterated a for loop from i = 0 to i < n. In each iteration of the loop, the user is asked to enter numbers to calculate the average. These numbers are stored in the num[] array.

scanf("%f", &num[i]);

And, the sum of each entered element is computed.

sum += num[i];

Once the for loop is completed, the average is calculated and printed on the screen.


C Example for Beginners: C Program to Calculate Average Using Arrays

Sign up to get end-to-end “Learn By Coding” example.

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.