Use a loop that adds \(1/i\) for \(i = 1\) to \(n\); for the second series keep a running factorial and add \(1/i!\).
(a) \(s = 1 + \frac12 + \frac13 + \dots + \frac1n\)
#include <stdio.h>
int main() {
int n, i;
float s = 0;
printf("Enter n: ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
s = s + 1.0 / i;
printf("Sum = %f\n", s);
return 0;
}
Writing 1.0 / i (not 1 / i) makes the division real; with integers, 1/2 would give 0.
(b) Modified: \(s = 1 + \frac1{2!} + \frac1{3!} + \dots + \frac1{n!}\)
#include <stdio.h>
int main() {
int n, i;
float s = 0, fact = 1;
printf("Enter n: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
fact = fact * i; /* now fact = i! */
s = s + 1 / fact;
}
printf("Sum = %f\n", s);
return 0;
}
In each pass fact is multiplied by i, so it holds \(i!\) without a separate inner loop. The first term is \(1/1! = 1\). For \(n = 3\): \(1 + 0.5 + 0.1667 = 1.6667\).