Q-03: Write a C/C++ to compute the sum of the first n terms of the following series.
S = 1 + 1/2 + 1/3 + 1/4 + . . . + n
    

Using - C


#include<stdio.h> void main() { int n, i; float sum=0; printf("Enter the number of terms: "); scanf("%d",&n); for(i=1; i<=n; i++){ sum += (float)1/i; } printf("Sum of the Series: %.2f",sum); }

OUTPUT

Enter the number of terms:  3
Sum of the Series:  1.83
        

Using - C++


#include<iostream> #include<iomanip> using namespace std; int main() { int n; float sum=0; cout<< "Enter the number of terms: "; cin>> n; for(int i=1; i<=n; i++){ sum += (float)1/i; } cout<< "Sum of the Series: "<< setprecision(3)<< sum; return 0; }

OUTPUT

Enter the number of terms:  9
Sum of the Series:  2.83