
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
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 Articles
- Complex numbers in C++ programming
- Realtime moving average of an array of numbers in JavaScript
- Average of a stream of numbers in C++
- Split Array With Same Average in C++
- Average of max K numbers in a stream in C++
- Fast average of two numbers without division in C++
- Splitting array of numbers into two arrays with same average in JavaScript
- Sum triangle from an array in C programming
- Explain array of pointers in C programming language
- Find the average of first N natural numbers in C++
- Maximum average sum partition of an array in C++
- Count pairs with average present in the same array in C++
- Array Size in Lua Programming
- Working with two-dimensional array at runtime in C programming
- Program for average of an array(Iterative and Recursive) in C++
