Home > Backend Development > C++ > In C programming, average numbers in an array

In C programming, average numbers in an array

WBOY
Release: 2023-08-27 13:25:06
forward
1883 people have browsed it

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

Method 1 - Iteration

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

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;
}
Copy after login

Method 2 - Recursive

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

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;
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template