The Wayback Machine - https://web.archive.org/web/20240707142047/https://www.geeksforgeeks.org/program-average-array-iterative-recursive/
Open In App

Program for average of an array (Iterative and Recursive)

Last Updated : 21 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

Examples : 

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

Input : arr[] = {5, 3, 6, 7, 5, 3}
Output : 4.83333
Sum of the elements is 5+3+6+7+5+3 = 29
and total number of elements is 6.
So average is 29/6 = 4.83333.

Iterative: 
Iterative program is easy. We need to find sum and divide sum by total number of elements. 

C++




// C++ program to calculate average of array elements
#include <iostream>
using namespace std;
 
// Function that return average of an array.
double average(int a[], int n)
{
    // Find sum of array element
    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;
}


Java




// Java program to calculate average of array elements
class GFG {
     
    // Function that return average of an array.
    static double average(int a[], int n)
    {
         
        // Find sum of array element
        int sum = 0;
         
        for (int i = 0; i < n; i++)
            sum += a[i];
     
        return (double)sum / n;
    }
     
    //driver code
    public static void main (String[] args)
    {
         
        int arr[] = {10, 2, 3, 4, 5, 6, 7, 8, 9};
        int n = arr.length;
     
        System.out.println(average(arr, n));
    }
}
 
// This code is contributed by Anant Agarwal.


Python3




# Python3 code to calculate
# average of array elements
 
# Function that return
# average of an array.
def average( a , n ):
 
    # Find sum of array element
    sum = 0
    for i in range(n):
        sum += a[i]
     
    return sum/n;
 
# Driver code
arr = [10, 2, 3, 4, 5, 6, 7, 8, 9]
n = len(arr)
print(average(arr, n))
 
# This code is contributed by "Shard_Bhardwaj".


C#




// C# program to calculate average of
// array elements
using System;
class GFG {
     
    // Function that return average of
    // an array.
    static double average(int []a, int n)
    {
         
        // Find sum of array element
        int sum = 0;
         
        for (int i = 0; i < n; i++)
            sum += a[i];
     
        return (double)sum / n;
    }
     
    // Driver code
    public static void Main ()
    {
         
        int []arr = {10, 2, 3, 4, 5, 6,
                                7, 8, 9};
        int n = arr.Length;
     
        Console.Write(average(arr, n));
    }
}
 
// This code is contributed by nitin mittal.


PHP




<?php
// PHP program to calculate average
// of array elements
 
// Function that return average of
// an array.
function average( $a, $n)
{
     
    // Find sum of array element
    $sum = 0;
    for ( $i = 0; $i < $n; $i++)
        $sum += $a[$i];
 
    return $sum / $n;
}
 
// Driver code
    $arr = array(10, 2, 3, 4, 5,
                        6, 7, 8, 9);
    $n = count($arr);
 
    echo average($arr, $n);
 
// This code is contributed by anuj_67.
?>


Javascript




<script>
      // JavaScript program to calculate average of array elements
 
      // Function that return average of an array.
      function average(a, n)
      {
       
        // Find sum of array element
        var sum = 0;
        for (var i = 0; i < n; i++) sum += a[i];
 
        return parseFloat(sum / n);
      }
 
      // Driver code
 
      var arr = [10, 2, 3, 4, 5, 6, 7, 8, 9];
      var n = arr.length;
 
      document.write(average(arr, n));
      document.write("<br>");
       
      // This code is contributed by rdtank.
    </script>


Output

6

Time Complexity: O(n)

Auxiliary Space: O(1)

Recursive: 
The idea is to pass index of element as an additional parameter and recursively compute sum. After computing sum, divide the sum by n.

C++




// C++ program to calculate average of array elements
#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)
{
     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;
}


Java




// Java program to calculate average
// of array elements
 
class CalcAvg
{
    // Recursively computes average of a[]
    static 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.
    static double average(int a[], int n)
    {
         return avgRec(a, 0, n);
    }
     
    // main function
    public static void main (String[] args)
    {
        int arr[] = {10, 2, 3, 4, 5, 6, 7, 8, 9};
        int n = arr.length;
      
        System.out.println(average(arr, n));
    }
}


Python3




# Python3 code to calculate
# average of array elements
 
# Recursively computes average of a[]
def avgRec( a , i , 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.
def average(a, n):
    return avgRec(a, 0, n)
 
# Driver code
arr = [10, 2, 3, 4, 5, 6, 7, 8, 9]
n = len(arr)
print(average(arr, n))
 
# This code is contributed by "Sharad_Bhardwaj".


C#




// C# program to calculate average
// of array elements
using System;
 
class GFG {
     
    // Recursively computes average of a[]
    static 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.
    static double average(int []a, int n)
    {
        return avgRec(a, 0, n);
    }
     
    // main function
    public static void Main ()
    {
        int []arr = {10, 2, 3, 4, 5, 6, 7, 8, 9};
        int n = arr.Length;
     
        Console.Write(average(arr, n));
    }
}
 
// This code is contributed by Smitha.


PHP




<?php
// PHP program to calculate
// average of array elements
 
// Recursively computes
// average of a[]
function avgRec($a, $i, $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.
function average($a, $n)
{
    return avgRec($a, 0, $n);
}
 
// Driver code
$arr = array(10, 2, 3, 4,
             5, 6, 7, 8, 9);
$n = sizeof($arr);
 
echo average($arr, $n) ;
 
// This code is contributed by Anuj_67
?>


Javascript




<script>
 
// Java script  program to calculate average
// of array elements
 
// Recursively computes average of a[]
function avgRec(a, i, 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.
function average(a, n)
{
    return avgRec(a, 0, n);
}
 
// Driver code
let arr = [ 10, 2, 3, 4, 5, 6, 7, 8, 9 ];
let n = arr.length;
 
document.write(average(arr, n));
 
// This code is contributed by sravan kumar G
 
</script>


Output

6

Time Complexity: O(n)

Auxiliary Space: O(n)

Related Article : 
Average of a stream of numbers



Similar Reads

Program to check if an array is sorted or not (Iterative and Recursive)
Given an array of size n, write a program to check if it is sorted in ascending order or not. Equal values are allowed in an array and two consecutive equal values are considered sorted. Examples: Input : 20 21 45 89 89 90Output : YesInput : 20 20 45 89 89 90Output : YesInput : 20 20 78 98 99 97Output : NoRecommended PracticeCheck if array is sorte
12 min read
Program to count vowels in a string (Iterative and Recursive)
Given a string, count the total number of vowels (a, e, i, o, u) in it. There are two methods to count total number of vowels in a string. Iterative Recursive Examples: Input : abc de Output : 2 Input : geeksforgeeks portal Output : 7Recommended PracticeVowel or NotTry It! 1. Iterative Method: Below is the implementation: C/C++ Code // C++ program
7 min read
Count consonants in a string (Iterative and recursive methods)
Given a string, count total number of consonants in it. A consonant is an English alphabet character that is not vowel (a, e, i, o and u). Examples of constants are b, c, d, f, and g. Examples : Input : abc de Output : 3 There are three consonants b, c and d. Input : geeksforgeeks portal Output : 12 1. Iterative Method C/C++ Code // Iterative CPP p
7 min read
First uppercase letter in a string (Iterative and Recursive)
Given a string find its first uppercase letterExamples : Input : geeksforgeeKs Output : K Input : geekS Output : S Method 1: linear search Using linear search, find the first character which is capital C/C++ Code // C++ program to find the first // uppercase letter using linear search #include &lt;bits/stdc++.h&gt; using namespace std; // Function
6 min read
Function to copy string (Iterative and Recursive)
Given two strings, copy one string to another using recursion. We basically need to write our own recursive version of strcpy in C/C++ Examples: Input : s1 = "hello" s2 = "geeksforgeeks" Output : s2 = "hello" Input : s1 = "geeksforgeeks" s2 = "" Output : s2 = "geeksforgeeks" Iterative: Copy every character from s1 to s2 starting from index = 0 and
6 min read
Check if linked list is sorted (Iterative and Recursive)
Given a Linked List, task is to check whether the Linked List is sorted in Descending order or not? Examples : Input : 8 -&gt; 7 -&gt; 5 -&gt; 2 -&gt; 1 Output : Yes Explanation : In given linked list, starting from head, 8 &gt; 7 &gt; 5 &gt; 2 &gt; 1. So, it is sorted in reverse order Input : 24 -&gt; 12 -&gt; 9 -&gt; 11 -&gt; 8 -&gt; 2 Output : N
8 min read
Find Length of a Linked List (Iterative and Recursive)
Write a function to count the number of nodes in a given singly linked list Examples: Input: Input: 2-&gt;4-&gt;1-&gt;9-&gt;5-&gt;3-&gt;6Output: 7 Recommended PracticeCount nodes of linked listTry It!An iterative approach for finding the length of the linked list:Follow the given steps to solve the problem: Initialize count as 0 Initialize a node p
15+ min read
Search an element in a Linked List (Iterative and Recursive)
Given a linked list and a key 'X' in, the task is to check if X is present in the linked list or not. Examples: Input: 14-&gt;21-&gt;11-&gt;30-&gt;10, X = 14Output: YesExplanation: 14 is present in the linked list. Input: 6-&gt;21-&gt;17-&gt;30-&gt;10-&gt;8, X = 13Output: No Using O(N) Extra Space. The Approach: In this approach we use vector where
15+ min read
Count half nodes in a Binary tree (Iterative and Recursive)
Given A binary Tree, how do you count all the half nodes (which has only one child) without using recursion? Note leaves should not be touched as they have both children as NULL. Input : Root of below treeOutput : 3 Nodes 7, 5 and 9 are half nodes as one of their child is Null. So count of half nodes in the above tree is 3 Iterative The idea is to
12 min read
Count full nodes in a Binary tree (Iterative and Recursive)
Given A binary Tree, how do you count all the full nodes (Nodes which have both children as not NULL) without using recursion and with recursion? Note leaves should not be touched as they have both children as NULL. Nodes 2 and 6 are full nodes has both child's. So count of full nodes in the above tree is 2 Method: Iterative The idea is to use leve
12 min read
Practice Tags :
three90RightbarBannerImg