Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Array Average in C++

Compute the average of n numbers stored in a C++ array, adding them up as they are read. Covers double for the sum, setprecision(2), and the n = 0 trap.

BeginnerArray ProgramsExample 2 of 4
array-average.cpp
1#include <iostream>
2#include <iomanip>
3using namespace std;
4
5int main() {
6 int n;
7 double sum = 0;
8
9 cout << "Enter number of elements: ";
10 cin >> n;
11
12 int arr[n];
13
14 cout << "Enter " << n << " elements: ";
15 for (int i = 0; i < n; i++) {
16 cin >> arr[i];
17 sum += arr[i];
18 }
19
20 double average = sum / n;
21
22 cout << fixed << setprecision(2);
23 cout << "Average of array elements: " << average << endl;
24
25 return 0;
26}

Sample Output

Average of array elements: 30.00

150 / 5, formatted to two decimals.

In this one

  • How to accumulate a sum while reading input
  • Why sum is double so the division keeps decimals
  • How fixed and setprecision format the result
  • How to guard against dividing by zero

How it works

  1. 1

    Read n (5).

  2. 2

    Read each element and add it to sum in the same loop.

  3. 3

    sum reaches 150.

  4. 4

    average = 150.0 / 5 = 30.0.

  5. 5

    Print 30.00.

Edge cases

n = 0

Enter 0.

sum / n becomes 0.0 / 0, which gives NaN for doubles (printed as nan or -nan). Check n > 0 first.

Average with a fraction

Enter 1 2.

sum is 3.0 and the average is 1.50. If sum were int, 3 / 2 would give 1.

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]

Sum = 10 + 20 + 30 + 40 + 50 = 150
Number of elements = 5
Average = 150 / 5 = 30.00

Header Files

The program uses two header files:

1.#include <iostream>
Provides cout for output and cin for input
2.#include <iomanip>
Provides fixed and setprecision() for formatting decimal output
Ensures the average is displayed with exactly 2 decimal places

Variable 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)
Uses double to handle decimal results accurately
arr[n]: The array to store the elements
Size is determined by user input n
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 double ensures accurate decimal calculations

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.

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

1cout << "Enter " << n << " elements: ";
2for (int i = 0; i < n; i++) {
3cin >> arr[i];
4sum += arr[i];
5}

Step-by-step:

1.The program asks the user to enter n elements
2.A loop runs from i = 0 to i < n (0-indexed)
3.For each iteration:
cin >> arr[i]; reads one element and stores it in the array
sum += 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 to sum = sum + arr[i];
This accumulates (adds up) all values as we read them
By the end of the loop, sum contains the total of all elements

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 = 5
average = 150.0 / 5 = 30.0

Formatting the Output

1cout << fixed << setprecision(2);
2cout << "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

Complete Program Flow

1.Ask user for number of elements (n)
2.Declare array of size n
3.Initialize sum = 0
4.Loop through array:
Read each element
Add to sum
5.Calculate average = sum / n
6.Format output to 2 decimal places
7.Display the average

Key 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)

1// First loop: Read elements
2for (int i = 0; i < n; i++) {
3cin >> arr[i];
4}
5// Second loop: Calculate sum
6for (int i = 0; i < n; i++) {
7sum += arr[i];
8}

Variation 2: Using float instead of double

1float sum = 0, average;
2// ... rest of code

Variation 3: Finding average of specific range

1// Average of first 3 elements only
2for (int i = 0; i < 3; i++) {
3sum += arr[i];
4}
5average = sum / 3;

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) {
2cout << "Error: Number of elements must be positive!" << endl;
3return 1;
4}

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Elements 1, 2, 2. What is printed?

Pick an answer to check it.

Question 2

What if sum were int and n = 4 with sum 10?

Pick an answer to check it.

Questions people ask

Why is sum double if the elements are int?

Dividing an int by an int truncates. A double sum makes the division keep the fraction.

Do I need to store the array at all?

Not for the average alone. You could just sum while reading. The array is useful if you later need the values again.

How do I round to the nearest whole number?

Use round(average) from <cmath>.