
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Arithmetic Mean in c++?
An arithmetic mean is the average of all the given numbers, which is calculated by summing all the numbers and dividing this calculated sum by the total number of elements. The formula for calculating the arithmetic mean is: $$ \bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i = \frac{x_1 + x_2 + x_3 + \cdots + x_n}{n} $$
Here, we are given an array of integers and our task is to calculate the arithmetic mean of these numbers using the above formula:
Scenario 1
Input: num = 2, 7, 4, 31, 21 Output: 13 Explanation: Arithmetic Mean = Sum of all numbers / Total number of elements Arithmetic Mean = (2 + 7 + 4 + 31 + 21) / 5 Arithmetic Mean = 65 / 5 = 13
Scenario 2
Input: num = 25, 17, 43, 22, 12 Output: 23.8 Explanation: Arithmetic Mean = (25 + 17 + 43 + 22 + 12) / 5 Arithmetic Mean = 119 / 5 = 23.8
Calculating Arithmetic Mean in C++
Following are the steps to calculate the arithmetic mean using the above formula:
- Input an array.
- Iterate over all the numbers in the array and calculate their sum.
- Divided this sum by the total number of elements to get the arithmetic mean.
C++ Program to Calculate Arithmetic Mean
In this example, we are calculating the arithmetic mean of 6 numbers using the above-mentioned formula.
#include <iostream> using namespace std; float aMean(float data[], int size) { float sum = 0; for (int i = 0; i < size; i++) { sum += data[i]; } return sum / size; } int main() { float num[] = {25.3, 45.21, 78.56, 96.21, 22.12, 36.97}; int size = sizeof(num) / sizeof(num[0]); cout << "Given numbers are: "; for (int i = 0; i < size; i++) { cout << num[i] << " "; } cout << "\nMean of the given numbers is: " << aMean(num, size); }
The output of the above code is as follows:
Given numbers are: 25.3 45.21 78.56 96.21 22.12 36.97 Mean of the given numbers is: 50.7283
Advertisements