#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int n;
double sum = 0;
cout << "Enter number of elements: ";
cin >> n;
int arr[n];
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
sum += arr[i];
}
double average = sum / n;
cout << fixed << setprecision(2);
cout << "Average of array elements: " << average << endl;
return 0;
}Output
Enter number of elements: 5 Enter 5 elements: 10 20 30 40 50 Average of array elements: 30.00
This program teaches you how to calculate the average of all elements in an array in C++. The average (also called the mean) is calculated by summing all elements and dividing by the total number of elements. This is a fundamental array operation that demonstrates how to iterate through arrays, accumulate values, and perform calculations with arrays.
1. What is an Array Average?
The average of an array is the sum of all elements divided by the number of elements.
Formula:
Average = (Element1 + Element2 + ... + ElementN) / N
Example:
If array = [10, 20, 30, 40, 50]
- Sum = 10 + 20 + 30 + 40 + 50 = 150
- Number of elements = 5
- Average = 150 / 5 = 30.00
2. Header Files
The program uses two header files:
-
#include <iostream>- Provides
coutfor output andcinfor input
- Provides
-
#include <iomanip>- Provides
fixedandsetprecision()for formatting decimal output - Ensures the average is displayed with exactly 2 decimal places
- Provides
3. Variable Declarations
cppint n; double sum = 0; int arr[n]; double average;
Explanation:
-
n: Stores the number of elements in the array (integer) -
sum: Accumulates the sum of all array elements (initialized to 0)- Uses
doubleto handle decimal results accurately
- Uses
-
arr[n]: The array to store the elements- Size is determined by user input
n
- Size is determined by user input
-
average: Stores the calculated average (double for decimal precision)
Why double for sum and average?
- Even if array elements are integers, the average might be a decimal
- Example: Average of [1, 2, 3] = 2.00 (decimal result)
- Using
doubleensures accurate decimal calculations
4. Taking 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.
5. 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.
6. Taking Input: Array Elements
cppcout << "Enter " << n << " elements: "; for (int i = 0; i < n; i++) { cin >> arr[i]; sum += arr[i]; }
Step-by-step:
- The program asks the user to enter
nelements - A loop runs from
i = 0toi < n(0-indexed) - For each iteration:
cin >> arr[i];reads one element and stores it in the arraysum += arr[i];adds the element to the running sum
Example with n = 5:
- User enters:
10 20 30 40 50 - Iteration 1:
arr[0] = 10,sum = 0 + 10 = 10 - Iteration 2:
arr[1] = 20,sum = 10 + 20 = 30 - Iteration 3:
arr[2] = 30,sum = 30 + 30 = 60 - Iteration 4:
arr[3] = 40,sum = 60 + 40 = 100 - Iteration 5:
arr[4] = 50,sum = 100 + 50 = 150
Key Technique: Accumulation
sum += arr[i];is equivalent tosum = sum + arr[i];- This accumulates (adds up) all values as we read them
- By the end of the loop,
sumcontains the total of all elements
7. Calculating 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.0
8. Formatting the Output
cppcout << fixed << setprecision(2); cout << "Average of array elements: " << average << endl;
fixed:
- Ensures numbers are displayed in fixed-point notation (not scientific notation)
- Example: 30.00 instead of 3e+01
setprecision(2):
- Sets the number of decimal places to 2
- Example: 30.0 becomes 30.00, 25.5 stays 25.50
Why format the output?
- Makes the result look professional and consistent
- Important for financial, scientific, and statistical applications
- Users expect a certain number of decimal places
9. Complete Program Flow
- Ask user for number of elements (
n) - Declare array of size
n - Initialize
sum = 0 - Loop through array:
- Read each element
- Add to sum
- Calculate average = sum / n
- Format output to 2 decimal places
- Display the average
10. Key Concepts Demonstrated
-
Array Input: Reading multiple values into an array using a loop
-
Accumulation Pattern: Using
sum += arr[i]to accumulate values is a common pattern in programming -
Type Conversion: Using
doubleensures decimal division even when dividing integers -
Output Formatting: Using
fixedandsetprecision()for professional-looking output -
Array Traversal: Iterating through all elements of an array using a for loop
11. Common Variations
Variation 1: Calculate average separately (two loops)
cpp// First loop: Read elements for (int i = 0; i < n; i++) { cin >> arr[i]; } // Second loop: Calculate sum for (int i = 0; i < n; i++) { sum += arr[i]; }
Variation 2: Using float instead of double
cppfloat sum = 0, average; // ... rest of code
Variation 3: Finding average of specific range
cpp// Average of first 3 elements only for (int i = 0; i < 3; i++) { sum += arr[i]; } average = sum / 3;
12. Common Mistakes
-
Not initializing sum: Forgetting
sum = 0gives incorrect results -
Integer division: Using
intfor sum/average loses decimal precision -
Wrong loop bounds: Using
i <= ninstead ofi < n(array out of bounds) -
Dividing by zero: If
n = 0, division by zero causes error -
Not formatting output: Missing
fixed << setprecision(2)gives inconsistent decimal places
13. 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
14. Edge Cases to Consider
-
Empty array:
n = 0→ Division by zero error -
Negative numbers: Works fine, but average might be negative
-
Very large numbers: May cause overflow if using
intfor sum -
Very small numbers: Precision issues with floating-point
Improved version with error checking:
cppif (n <= 0) { cout << "Error: Number of elements must be positive!" << endl; return 1; }
Summary
- The program reads
nelements into an array. - It accumulates the sum of all elements using
sum += arr[i]in a loop. - The average is calculated as
sum / n. doubleis used for sum and average to ensure decimal precision.- Output is formatted to 2 decimal places using
fixed << setprecision(2). - This creates a clean, professional program for calculating array averages.
This program is essential for understanding array operations, accumulation patterns, and output formatting. It's a fundamental building block for more complex array manipulations and statistical calculations.