Back to C Programming
2026-07-145 min read

Calculate Average Using Arrays

Learn Calculate Average Using Arrays step by step with clear examples and exercises.

Why This Matters

Calculating the average of a set of numbers is a fundamental operation in programming, and arrays are an efficient way to store these numbers for easy manipulation. In this lesson, we'll delve deeper into understanding how to calculate the average of an array of numbers using C programming.

Knowing how to work with arrays and calculate averages is essential for any serious C programmer as it plays a crucial role in various real-world applications such as analyzing data from sensors, processing financial transactions, or even grading students.

Prerequisites

Before diving into the core concept, you should have a solid understanding of the following C programming topics:

  • Data types (int, float, etc.)
  • Variables and constants
  • Input/Output operations using scanf() and printf()
  • Control structures like if...else and loops (for, while)
  • Arrays, pointers, and dynamic memory allocation (malloc(), realloc())

Core Concept

To calculate the average of an array, we first need to store the numbers in the array and then find the sum of these numbers. After that, we can simply divide the sum by the number of elements in the array to get the average. Here's a step-by-step breakdown:

  1. Declare the array and variables for the number of elements, sum, and average.
  2. Read the number of elements from the user and check if it is within the valid range (e.g., 1 to 100). If not, prompt the user to enter a valid number.
  3. Allocate memory dynamically using malloc() for the array if the number of elements exceeds the predefined size.
  4. Use a loop to read each number from the user and store it in the array.
  5. Calculate the sum of all numbers using a loop.
  6. Divide the sum by the number of elements to get the average.
  7. Print the calculated average.
  8. Free the dynamically allocated memory when done with the program.

Here's an example code that demonstrates this process:

#include <stdio.h>
#include <stdlib.h>

int main() {
int n, i;
float *num, sum = 0.0, avg;

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

// Check if the entered number is valid
if (n > 100 || n < 1) {
printf("Error! Number should be between 1 and 100.\n");
return -1;
}

// Allocate memory for the array
num = (float *)malloc(n * sizeof(float));

// Read numbers from the user and store them in the array
for (i = 0; i < n; ++i) {
printf("%d. Enter number: ", i + 1);
scanf("%f", &num[i]);
sum += num[i];
}

// Calculate and print the average
avg = sum / n;
printf("Average = %.2f\n", avg);

// Free the dynamically allocated memory
free(num);

return 0;
}

Worked Example

Let's walk through an example to understand how this code works:

  1. The user enters 6 as the number of elements.
  2. The program checks if the entered number is valid (between 1 and 100). Since it is, the program continues.
  3. The program dynamically allocates memory for the array num.
  4. The loop reads each number from the user and stores it in the array:
  • For the first element, the user enters 45.3. This value gets stored at num[0], and sum gets updated to 45.3.
  • For the second element, the user enters 67.5. This value gets stored at num[1], and sum gets updated to 112.8.
  • And so on...
  1. After reading all numbers, the program calculates the average: sum / n = 112.8 / 6 = 18.80.
  2. The program prints the calculated average: Average = 18.80.
  3. The program frees the dynamically allocated memory before exiting.

Common Mistakes

Here are some common mistakes to avoid when working with arrays and calculating averages in C programming, along with explanations for each:

1. Invalid number of elements

Ensure that the user enters a valid number of elements within the specified range (e.g., between 1 and 100). If not, prompt the user to enter a valid number and repeat the process until they do.

2. Incorrect data type for sum and average

Use float instead of int for the variables sum and avg. This is because the sum and average can contain decimal numbers, and using int would result in an incorrect calculation.

3. Not updating sum correctly

Make sure to update the sum variable after reading each number from the user inside the loop.

4. Forgetting to free dynamically allocated memory

Always remember to free the dynamically allocated memory when done with the program to avoid memory leaks.

Practice Questions

  1. Modify the example code to handle negative numbers as well. Calculate the average of all positive numbers and the average of all negative numbers separately.
  2. Write a program that calculates the average of an array of numbers using pointers instead of indices, dynamically allocating memory for both the array and a separate variable for the sum.
  3. Write a program that finds the average of three subjects (Math, Science, English) from user input and prints the overall percentage based on a weighted average where Math has a weight of 0.4, Science has a weight of 0.5, and English has a weight of 0.1. The grades for each subject should be entered as integers between 0 and 100.
  4. Write a program that calculates the mean, median, and mode of an array of numbers using C programming.

FAQ

Q: Why can't I use int for sum and average?

A: Using int would cause the program to truncate decimal numbers, resulting in an incorrect calculation. Since averages often involve decimal numbers, it is better to use float.

Q: How can I handle more than 100 elements in the array?

A: To handle more than 100 elements, you need to allocate memory dynamically using functions like malloc() and realloc(). This allows you to create arrays of any size during runtime.

Q: How can I find the average of a subarray within an array?

A: To find the average of a subarray, you can use a loop to iterate through the subarray and calculate the sum. Then, divide the sum by the number of elements in the subarray to get the average. You may need to allocate memory dynamically for the subarray if it exceeds the size of the original array.

Q: How do I find the mode of an array?

A: To find the mode of an array, you can use a frequency table or count the occurrences of each number in the array and find the one with the highest frequency. If there are multiple numbers with the same highest frequency, they are all modes of the array.