English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Others

C Language Reference Manual

C program to calculate the average using an array

Comprehensive Collection of C Programming Examples

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

To understand this example, you should understand the followingC programming languageTopic:

Using an array to store numbers and calculate the average

#include <stdio.h>
int main() {
    int n, i;
    float num[100], sum = 0.0, avg;
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    while (n > 100 || n < 1) {
        printf("Error! The number should be in the range of ( ",1 - 100).\n");
        printf("Enter the number again: ");
        scanf("%d", &n);
    }
    for (i = 0; i < n; ++i) {
        printf("%d. Enter a number: ", i + 1);
        scanf("%f", &num[i]);
        sum += num[i];
    }
    avg = sum / n;
    printf("Average (Average) = %.2f", avg);
    return 0;
}

Output result

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

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

If the integer entered by the user is greater than1or greater than10If the number is 0, the user is asked to enter the number again. This is done using a while loop.

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

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

And, calculate the sum of each input element.

sum += num[i];

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

Comprehensive Collection of C Programming Examples