

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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; }
- Related Questions & Answers
- Complex numbers in C++ programming
- Average of a stream of numbers in C++
- Realtime moving average of an array of numbers in JavaScript
- Split Array With Same Average in C++
- Fast average of two numbers without division in C++
- Average of max K numbers in a stream in C++
- Find the average of first N natural numbers in C++
- Splitting array of numbers into two arrays with same average in JavaScript
- Maximum average sum partition of an array in C++
- C++ Program to Calculate Average of Numbers Using Arrays
- Average of Squares of Natural Numbers?
- Sum triangle from an array in C programming
- Explain array of pointers in C programming language
- Count pairs with average present in the same array in C++
- Calculate average of numbers in a column MySQL query?