Write a recursive function float harm_rec(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_rec(int n)
{
if (n==1)
return 1;
else
return 1.0/n + harm_rec(n-1);
}
void main()
{
int n;
do{
printf("Enter n: ");
scanf("%d",&n);
}while(n<=0);
printf("Value = %f\n", harm_rec(n));
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Removing a sequence of 3 characters from a string