Mean of array using recursion
To find the mean of the elements of the array.
Mean = (Sum of elements of the Array) /
(Total no of elements in Array)
Examples:
Input : 1 2 3 4 5
Output : 3
Input : 1 2 3
Output : 2
To find the mean using recursion assume that the problem is already solved for N-1 ie you have to find for n
Sum of first N-1 elements =
(Mean of N-1 elements)*(N-1)
Mean of N elements = (Sum of first N-1 elements +
N-th elements) / (N)
Note : Since array indexing starts from 0, we access N-th element using A[N-1].
Implementation:
C++
#include <iostream>
using namespace std;
float findMean( int A[], int N)
{
if (N == 1)
return ( float )A[N-1];
else
return (( float )(findMean(A, N-1)*(N-1) +
A[N-1]) / N);
}
int main()
{
float Mean = 0;
int A[] = {1, 2, 3, 4, 5};
int N = sizeof (A)/ sizeof (A[0]);
cout << " " << findMean(A, N);
return 0;
}
|
C
#include<stdio.h>
float findMean( int A[], int N)
{
if (N == 1)
return ( float )A[N-1];
else
return (( float )(findMean(A, N-1)*(N-1) +
A[N-1]) / N);
}
int main()
{
float Mean = 0;
int A[] = {1, 2, 3, 4, 5};
int N = sizeof (A)/ sizeof (A[0]);
printf ( "%.2f\n" , findMean(A, N));
return 0;
}
|
Java
import java.io.*;
class CalcMean
{
static float findMean( int A[], int N)
{
if (N == 1 )
return ( float )A[N- 1 ];
else
return (( float )(findMean(A, N- 1 )*(N- 1 ) +
A[N- 1 ]) / N);
}
public static void main (String[] args)
{
float Mean = 0 ;
int A[] = { 1 , 2 , 3 , 4 , 5 };
int N = A.length;
System.out.println(findMean(A, N));
}
}
|
Python3
def findMean(A, N):
if (N = = 1 ):
return A[N - 1 ]
else :
return ((findMean(A, N - 1 ) *
(N - 1 ) + A[N - 1 ]) / N)
Mean = 0
A = [ 1 , 2 , 3 , 4 , 5 ]
N = len (A)
print (findMean(A, N))
|
C#
using System;
class CalcMean
{
static float findMean( int []A, int N)
{
if (N == 1)
return ( float )A[N - 1];
else
return (( float )(findMean(A, N - 1) *
(N - 1) + A[N - 1]) / N);
}
public static void Main()
{
int []A = {1, 2, 3, 4, 5};
int N = A.Length;
Console.WriteLine(findMean(A, N));
}
}
|
PHP
<?php
function findMean( $A , $N )
{
if ( $N == 1)
return $A [ $N - 1];
else
return ((findMean( $A , $N - 1) * ( $N - 1) +
$A [ $N - 1]) / $N );
}
$Mean = 0;
$A = array (1, 2, 3, 4, 5);
$N = sizeof( $A );
echo findMean( $A , $N );
?>
|
Javascript
<script>
function findMean(A, N)
{
if (N == 1)
return A[N - 1];
else
return ((findMean(A, N - 1) * (N - 1) + A[N - 1]) / N);
}
let A = [1, 2, 3, 4, 5];
let N = A.length;
document.write(findMean(A, N));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Last Updated :
19 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...