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

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find sum of series 1 + ½ + ? + ¼ + … +1/n

For this we will be provided with the value of n. Our task is to calculate the sum of the series upto the given value and print it out.

Example

 Live Demo

#include <iostream>
using namespace std;
//returning the sum of given series
class sum_series {
   public : double sum(int n) {
      double i, s = 0.0;
      for (i = 1; i <= n; i++)
         s = s + 1/i;
      return s;
   }
};
int main() {
   sum_series g;
   int n = 5;
   cout << "Sum is " << g.sum(n);
   return 0;
}

Output

Sum is 2.28333
raja
Published on 27-May-2020 13:14:45
Advertisements