Home > Article > Backend Development > In C programming, average numbers in an array
# n elements are stored in the array and the program calculates the average of these numbers. Use different methods.
Input- 1 2 3 4 5 6 7
Output- 4
Description- The sum of the elements of array 1 2 3 4 5 6 7=28
The number of elements in the array=7
Average=28/7=4
There are two methods
In this method we will sum and divide the sum of the total number of elements.
Given the size of array arr[] and array n
Input- 1 2 3 4 5 6 7
Output- 4
Explanation- The sum of the elements of the array 1 2 3 4 5 6 7 = 28
The number of elements in the array = 7
Average=28/7=4
#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; }
The idea is to pass the element index as an additional parameter and calculate the sum recursively. After calculating the sum, divide the sum by n.
Given the array arr[], the size of the array n and the initial index i
Input- 1 2 3 4 5
Output - 3
Explanation- The sum of array elements 1 2 3 4 5= 15
The number of elements in the array=5
average =15/5=3
#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; }
The above is the detailed content of In C programming, average numbers in an array. For more information, please follow other related articles on the PHP Chinese website!