Array Average in C++
Calculate average of array elements in C++.
1#include <iostream>2#include <iomanip>3using namespace std;45int main() {6 int n;7 double sum = 0;89 cout << "Enter number of elements: ";10 cin >> n;1112 int arr[n];1314 cout << "Enter " << n << " elements: ";15 for (int i = 0; i < n; i++) {16 cin >> arr[i];17 sum += arr[i];18 }1920 double average = sum / n;2122 cout << fixed << setprecision(2);23 cout << "Average of array elements: " << average << endl;2425 return 0;26}
Output
Enter number of elements: 5 Enter 5 elements: 10 20 30 40 50 Average of array elements: 30.00
What's going on
What is an Array Average?
The average of an array is the sum of all elements divided by the number of elements.
Formula:
1Average = (Element1 + Element2 + ... + ElementN) / N
Example:
If array = [10, 20, 30, 40, 50]
Header Files
The program uses two header files:
1.
`#include <iostream>`
cout for output and cin for input2.
`#include <iomanip>`
fixed and setprecision() for formatting decimal outputVariable Declarations
1int n;2double sum = 0;3int arr[n];4double average;
Explanation:
-
`n`
: Stores the number of elements in the array (integer)
-
`sum`
: Accumulates the sum of all array elements (initialized to 0)
double to handle decimal results accurately-
`arr[n]`
: The array to store the elements
n-
`average`
: Stores the calculated average (double for decimal precision)
Why `double` for sum and average?
double ensures accurate decimal calculationsTaking Input: Number of Elements
cout << "Enter number of elements: ";
cin >> n;
The program first asks the user how many elements they want to enter. This determines the size of the array.
Example:
If user enters 5, then n = 5, and the array will have 5 elements.
Declaring the Array
int arr[n];
This creates an array of size n to store the elements.
Note:
Variable-length arrays (VLAs) like this work in some C++ compilers, but the standard approach is to use vectors or dynamic allocation. However, for beginners, this syntax is simpler to understand.
Taking Input: Array Elements
1for (int i = 0; i < n; i++) {2cin >> arr[i];3sum += arr[i];4}
1cout << "Enter " << n << " elements: ";
Step-by-step:
n elementsi = 0 to i < n (0-indexed)cin >> arr[i]; reads one element and stores it in the arraysum += arr[i]; adds the element to the running sumExample with n = 5:
10 20 30 40 50arr[0] = 10, sum = 0 + 10 = 10arr[1] = 20, sum = 10 + 20 = 30arr[2] = 30, sum = 30 + 30 = 60arr[3] = 40, sum = 60 + 40 = 100arr[4] = 50, sum = 100 + 50 = 150Key Technique: Accumulation
sum += arr[i]; is equivalent to sum = sum + arr[i];sum contains the total of all elementsCalculating the Average
double average = sum / n;
This line calculates the average by dividing the sum by the number of elements.
Important:
Since both sum and average are double, the division will be floating-point division, giving a decimal result.
Example:
sum = 150 (as double: 150.0)n = 5average = 150.0 / 5 = 30.0Formatting the Output
1
1cout << fixed << setprecision(2);2cout << "Average of array elements: " << average << endl;
`fixed`
:
`setprecision(2)`
:
Why format the output?
Complete Program Flow
n)nsum = 0Key Concepts Demonstrated
1.
Array Input
: Reading multiple values into an array using a loop
2.
Accumulation Pattern
: Using sum += arr[i] to accumulate values is a common pattern in programming
3.
Type Conversion
: Using double ensures decimal division even when dividing integers
4.
Output Formatting
: Using fixed and setprecision() for professional-looking output
5.
Array Traversal
: Iterating through all elements of an array using a for loop
Common Variations
Variation 1: Calculate average separately (two loops)
1for (int i = 0; i < n; i++) {2cin >> arr[i];3}45// Second loop: Calculate sum6for (int i = 0; i < n; i++) {7sum += arr[i];8}
1// First loop: Read elements
Variation 2: Using float instead of double
1float sum = 0, average;
1// ... rest of code
Variation 3: Finding average of specific range
1for (int i = 0; i < 3; i++) {2sum += arr[i];3}4average = sum / 3;
1// Average of first 3 elements only
Common Mistakes
1.
Not initializing sum
: Forgetting sum = 0 gives incorrect results
2.
Integer division
: Using int for sum/average loses decimal precision
3.
Wrong loop bounds
: Using i <= n instead of i < n (array out of bounds)
4.
Dividing by zero
: If n = 0, division by zero causes error
5.
Not formatting output
: Missing fixed << setprecision(2) gives inconsistent decimal places
Practical Applications
Array averages are used in:
-
Statistics
: Calculating mean values
-
Data Analysis
: Analyzing datasets
-
Grading Systems
: Calculating student averages
-
Performance Metrics
: Average scores, times, etc.
-
Financial Calculations
: Average prices, returns, etc.
-
Scientific Computing
: Average measurements, readings
Edge Cases to Consider
1.
Empty array
: n = 0 → Division by zero error
2.
Negative numbers
: Works fine, but average might be negative
3.
Very large numbers
: May cause overflow if using int for sum
4.
Very small numbers
: Precision issues with floating-point
Improved version with error checking:
1if (n <= 0) {2}
1cout << "Error: Number of elements must be positive!" << endl;2return 1;