Write an iterative function $\texttt{float harm_it(int n)}$ which computes the sum of the first n terms of the harmonic series (n is passed in parameter): \(1 + \frac{1}{2} + \frac{1}{3} + \cdots + \frac{1}{n}\)
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
float harm_it(int n)
{
float res=0.0;
int i;
for (i=1; i<=n; i++)
res=res+1.0/i;
return res;
}
void main()
{
int n;
do{
printf("Enter n: ");
scanf("%d",&n);
}while(n<=0);
printf("Value = %f\n", harm_it(n));
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Display the addition sign of 2 integers without performing the sum