Program to find sum of series 1 + 1/2 + 1/3 + 1/4 + .. + 1/n in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number n. Our task is to create a program to find sum of series 1 + 1/2 + 1/3 + 1/4 + .. + 1/n in C++.

Code description − Here, we will find the sum of the series 1 + 1/2 + 1/3 + 1/4 + .. + 1/n till nth term. The series is a harmonic progression series.

Harmonic progression is a series whose inverse will be an arithmetic progression. I.e. if for a harmonic progression A1, A2, A3... An, there is an arithmetic progression 1/A1, 1/A2, 1/A3.

First, let’s take an example to understand the problem,

Input

n = 5

Output

2.59286

Explanation

Sum = 1 + ½ + ⅓ + ¼ + ⅕ + ⅙ + 1/7 = 2.59286

Solution Approach

To solve the problem, we will simply use the loops as there is no specif formula for the sum of HP.

Algorithm

Initialize − sumVal = 0;

• Step 1 − Loop for i -> 1 to n.
• Step 1.1 − Update sumVal, sumVal += 1/i.
• Step 2 − Print sumVal.

Program to illustrate the working of our solution

Example

Live Demo

#include <iostream>
using namespace std;
float calcSeriesSum(int n){
float sumVar = 0.00;
for(float i = 1; i <= n; i++){
sumVar += (1/i);
}
return sumVar;
}
int main(){
int n = 7;
cout<<"The sum of series till "<<n<<" is "<<calcSeriesSum(n);
return 0;
}

Output

The sum of series till 7 is 2.59286
Published on 27-May-2020 09:44:45