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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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