# Program for harmonic mean of numbers in C++

Given with an array of natural numbers and the task is to calculate the harmonic mean of given numbers and print it.

## What is harmonic mean?

Harmonic mean means the reciprocal of the arithmetic mean by their reciprocals.

$$Harmonic\: Mean=\frac{n}{\frac{1}{a}+\frac{1}{b}+\frac{1}{c}+...}$$

Where, n is the total number of elements given and a, b, c,.. are the actual elements in an array.

Steps to calculate the harmonic mean are

• Do the reciprocal of the elements

• Add all the reciprocated elements together

• Now divide the total number of elements in an array by the sum of reciprocated elements

Input

arr[] = {2.0, 3.4, 5.3, 2.1}

Output

Harmonic mean is: 2.74163

Input

arr[] = {13.5, 14.5, 14.8, 15.2, 16.1}

Output

Harmonic mean is : 14.7707

## Algorithm

Start
Step 1→ declare function to calculate harmonic mean of numbers
float harmonic_mean(float arr[], int size)
Declare float sum = 0
Loop For int i = 0 and i < size and i++
Set sum = sum + (float)1 / arr[i]
End
return (float)size/sum
Step 2→ In main()
Declare float arr[] = {2.0, 3.4, 5.3, 2.1}
Declare int size = sizeof(arr) / sizeof(arr)
Call harmonic_mean(arr, size)
Stop

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
//calculate harmonic mean
float harmonic_mean(float arr[], int size){
float sum = 0;
for (int i = 0; i < size; i++)
sum = sum + (float)1 / arr[i];
return (float)size/sum;
}
int main(){
float arr[] = {2.0, 3.4, 5.3, 2.1};
int size = sizeof(arr) / sizeof(arr);
cout<<"Harmonic mean is : "<<harmonic_mean(arr, size);
return 0;
}

## Output

If run the above code it will generate the following output −

Harmonic mean is : 2.74163