Program for average of an array (Iterative and Recursive)
Last Updated :
21 Aug, 2022
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>
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>
Time Complexity: O(n)
Auxiliary Space: O(n)
Related Article :
Average of a stream of numbers
Similar Reads
Program for Variance and Standard Deviation of an array Given an array, we need to calculate the variance and standard deviation of the elements of the array. Examples : Input : arr[] = [1, 2, 3, 4, 5]Output : Variance = 2 Standard Deviation = 1 Input : arr[] = [7, 7, 8, 8, 3]Output : Variance = 3 Standard Deviation = 1We have discussed program to find m
9 min read
Generate an Array such that Average of triplet exist in given Array Given an array A[] of length N and your task is to find an array B[] of size N+2, such that Average of (B[i], B[i+1], B[i+2]) equals to A[i] for each i (1 <= i <= N) . Note: First two elements B[] must be zero. Examples:Input: N = 1, A[] = {3} Output: B[] = {0, 0, 9} Explanation: Let us unders
5 min read
Count of Unique elements after inserting average of MEX and Array Max K times Given an array A[] of N non-negative integers and an integer K. Each time, you can do the following two operations Find Average of MAX and MEX(rounded up to closest greater integer) of the array.Insert calculated average in the array. After performing the above operation K times, find the count of u
9 min read
Maximum average sum partition of an array Given an array, we partition a row of numbers A into at most K adjacent (non-empty) groups, then the score is the sum of the average of each group. What is the maximum score that can be scored? Examples: Input : A = { 9, 1, 2, 3, 9 } K = 3 Output : 20 Explanation : We can partition A into [9], [1, 2
10 min read
Program to find average of all nodes in a Linked List Given a singly linked list. The task is to find the average of all nodes of the given singly linked list. Examples: Input: 7->6->8->4->1 Output: 26 Average of nodes: (7 + 6 + 8 + 4 + 1 ) / 5 = 5.2 Input: 1->7->3->9->11->5 Output: 6 Iterative Solution: Initialise a pointer
6 min read
Numbers of pairs from an array whose average is also present in the array Given an array arr[] consisting of N integers, the task is to count the number of distinct pairs (arr[i], arr[j]) in the array such that the average of pairs is also present in the array. Note: Consider (arr[i], arr[j]) and (arr[j], arr[i]) as the same pairs. Examples: Input: arr[] = {2, 1, 3}Output
15 min read
Javascript Program for Mean of range in array Given an array of n integers. You are given q queries. Write a program to print the floor value of mean in range l to r for each query in a new line.Examples : Input : arr[] = {1, 2, 3, 4, 5} q = 3 0 2 1 3 0 4 Output : 2 3 3 Here for 0 to 2 (1 + 2 + 3) / 3 = 2 Input : arr[] = {6, 7, 8, 10} q = 2 0 3
3 min read
Replace all elements of given Array with average of previous K and next K elements Given an array arr[] containing N positive integers and an integer K. The task is to replace every array element with the average of previous K and next K elements. Also, if K elements are not present then adjust use the maximum number of elements available before and after. Examples: Input: arr[] =
11 min read
Program to find simple moving average | Set-2 Simple Moving Average is the average obtained from the data for some t period of time . In normal mean, its value get changed with the changing data but in this type of mean it also changes with the time interval. We get the mean for some period t and then we remove some previous data. Again we get
5 min read
Break an array into maximum number of sub-arrays such that their averages are same Given an integer array, the task is to divide the array into the maximum number of sub-arrays such that the averages of all subarrays are the same. If it is not possible to divide, then print "Not possible". Examples: Input : arr[] = {1, 5, 7, 2, 0}; Output : (0 1) (2 4) Subarrays arr[0..1] and arr[
8 min read