Average numbers in array in C Programming


There are n number of elements stored in an array and this program calculates the average of those numbers. Using different methods.

Input - 1 2 3 4 5 6 7

Output - 4

Explanation - Sum of elements of array 1+2+3+4+5+6+7=28

No of element in array=7

Average=28/7=4

There are two methods

Method 1:Iterative

In this method we will find sum and divide the sum by the total number of elements.

Given array arr[] and size of array n

Input - 1 2 3 4 5 6 7

Output - 4

Explanation - Sum of elements of array 1+2+3+4+5+6+7=28

No of element in array=7

Average=28/7=4

Example

#include<iostream>
using namespace std;
int main() {
   int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
   int n=7;
   int sum = 0;
   for (int i=0; i<n; i++) {
      sum += arr[i];
   }
   float average = sum/n;
   cout << average;
   return 0;
}

Method 2: 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.

Given array arr[], size of array n and initial index i

Input - 1 2 3 4 5

Output - 3

Explanation - Sum of elements of array 1+2+3+4+5=15

No of element in array=5

Average=15/5=3

Example

#include <iostream>
using namespace std;
int avg(int arr[], int i, int n) {
   if (i == n-1) {
      return arr[i];
   }
   if (i == 0) {
      return ((arr[i] + avg(arr, i+1, n))/n);
   }
   return (arr[i] + avg(arr, i+1, n));
}
int main() {
   int arr[] = {1, 2, 3, 4, 5};
   int n = 5;
   cout << avg(arr,0, n) << endl;
   return 0;
}
raja
Published on 09-Aug-2019 16:55:59
Advertisements