C++ Program For Average of an Array (Iterative and Recursive)

Last Updated : 31 Mar, 2026

Given an array, the task is to find the average of that array. Average is the sum of the array elements divided by the number of elements. For Example:

Input: arr[] = {1, 2, 3, 4, 5}
Output: 3

  • Sum of the elements is 1+2+3+4+5 = 15
  • and total number of elements is 5.
  • So average is 15/5 = 3

Below are different approaches:

Iterative Approach

  1. Iterate each element of an array using a loop.
  2. Sum up each element of the array till we reach the end of the array.
  3. Divide the sum by the total number of elements and return the average
C++
#include <iostream>
using namespace std;

// Function that return average
// of an array.
double average(int a[], int n)
{
    if (n == 0)
        return 0; // handle empty array

    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += a[i];

    return (double)sum / n;
}

// Driver code
int main()
{
    int arr[] = { 10, 2, 3, 4, 5, 6, 7, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);

    cout << average(arr, n) << endl;
    return 0;
}

Output
6
  • Time Complexity: O(n), The time complexity of the above code is O(n) as it loops through all elements of the array to calculate the sum. 
  • Auxiliary Space: O(1), The space complexity is O(1) as no extra space is used.

Recursive Approach

  1. We will call the function again and again till we reach the end of an array.
  2. We will sum every element of the array and when we reach the end of an array, we will return the average of the array.
C++
#include <iostream>
using namespace std;

// Recursively computes average
// of a[]
double avgRec(int a[], int i, int n)
{
    // Last element
    if (i == n - 1)
        return a[i];

    // When index is 0, divide sum
    // computed so far by n.
    if (i == 0)
        return ((a[i] + avgRec(a, i + 1, n)) / n);

    // Compute sum
    return (a[i] + avgRec(a, i + 1, n));
}

// Function that return average
// of an array.
double average(int a[], int n) {
    if (n == 0)
        return 0; // handle empty array
    return avgRec(a, 0, n);
}

// Driver code
int main()
{
    int arr[] = { 10, 2, 3, 4, 5, 6, 7, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);

    cout << average(arr, n) << endl;
    return 0;
}

Output
6
  • Time Complexity: O(n)
  • Auxiliary Space: O(n)

Related Article: 

Average of a stream of numbers

Comment