C Program to Calculate Average Using Arrays

1. Introduction

Arrays in C provide an efficient way to store and process a collection of data. Calculating the average of a set of numbers is a fundamental operation and is especially straightforward when using arrays. This post will guide you through a C program that calculates the average of a set of numbers using arrays.

2. Program Overview

1. Define the array and its size.

2. Prompt the user to input numbers into the array.

3. Calculate the sum of all elements in the array.

4. Divide the sum by the number of elements to get the average.

5. Display the calculated average.

3. Code Program

#include <stdio.h>

int main() {
    int n, i;
    float sum = 0.0, average;

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

    float num[n];

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

    average = sum / n;
    printf("Average = %.2f\n", average);

    return 0;
}

Output:

Enter the numbers of data: 5
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40
Enter number 5: 50
Average = 30.00

4. Step By Step Explanation

1. After defining the necessary variables, the user is prompted to specify how many numbers they wish to input.

2. We then define an array num of float type to hold the user's numbers.

3. A for loop iterates n times, prompting the user to enter each number, which is stored in the array. As each number is entered, it's added to the sum.

4. After collecting all numbers, we calculate the average by dividing the sum by n, the number of data points.

5. The result, average, is then printed to the screen.

Comments