Calculate Average of N Numbers in C++
The average of a set of numbers is calculated by summing all the numbers and then dividing by the count of numbers. This guide explains how to calculate the average of n numbers in C++ with a complete implementation and interactive calculator.
How to Calculate the Average
The average (mean) of a set of numbers is calculated using this simple formula:
Average = (Sum of all numbers) / (Count of numbers)
To calculate the average in C++, you need to:
- Read the numbers from the user or from an array
- Sum all the numbers
- Count how many numbers there are
- Divide the sum by the count
- Display the result
Note: The average is sensitive to outliers. If one number is much larger or smaller than the others, it can significantly affect the average.
C++ Implementation
Here's a complete C++ program that calculates the average of n numbers:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int n;
double sum = 0.0, average;
cout << "Enter the number of elements: ";
cin >> n;
double numbers[n];
cout << "Enter " << n << " numbers:" << endl;
for(int i = 0; i < n; i++) {
cin >> numbers[i];
sum += numbers[i];
}
average = sum / n;
cout << fixed << setprecision(2);
cout << "The average is: " << average << endl;
return 0;
}
The program:
- Declares variables for the count of numbers, sum, and average
- Prompts the user to enter the number of elements
- Creates an array to store the numbers
- Uses a loop to read each number and add it to the sum
- Calculates the average by dividing the sum by the count
- Displays the result with 2 decimal places
Worked Example
Let's calculate the average of these 5 numbers: 12, 15, 18, 20, 25.
Sum = 12 + 15 + 18 + 20 + 25 = 90
Count = 5
Average = 90 / 5 = 18
The average of these numbers is 18. You can verify this using the calculator below.
FAQ
double data type to store and calculate averages with decimal places.