π₯ C Program to Calculate Sum of Series (1/1! + 2/2! + ... + N/N!) using Do-While Loop
Want to learn how to solve the Factorial Series using a do-while loop? π€
In this example, we calculate the sum of the series 1/1! + 2/2! + ... + N/N! in a simple, step-by-step way.
π Remember: Factorial of N (N!) is the product of all positive integers up to N (e.g., 3! = 3 Γ 2 Γ 1 = 6).
π» C Program Code
#include <stdio.h>
int main() {
int i = 1, j, n, fact;
float total = 0.0;
printf("Enter the value of N: ");
scanf("%d", &n);
// Using do-while to ensure the series calculates at least once
do {
fact = 1;
j = 1;
// Inner loop to calculate factorial
while(j <= i) {
fact *= j;
j++;
}
total += ((float)i / fact);
printf("%d/%d!", i, fact);
if(i < n) printf(" + ");
i++;
} while(i <= n);
printf("\nSum of Series = %.2f\n", total);
return 0;
}
π Output
Enter the value of N: 3
1/1! + 2/2! + 3/6!
Sum of Series = 2.50
π§ Easy Explanation (Understand in 30 Seconds)
β Step 1: Initialize total = 0.0 and start outer loop with i = 1.
β Step 2: Inner loop calculates fact for the current i.
β Step 3: Add (float)i / fact to total.
β Step 4: Increase i by 1.
β Step 5: Repeat until i exceeds N (Do-While checks condition at the end).
β‘ Important Concept (Must Know)
π In a do-while loop, the code block executes at least once before the condition is checked.
π Always cast to (float) during division to avoid integer division errors which result in 0.
π― Why This Program is Important?
β Tests your knowledge of nested loops.
β Common in exams and technical interviews.
β Essential for understanding data type casting in C.
π Try This Yourself
π Can you modify this to calculate the sum of 1/2! + 2/3! + ...?
π Try printing the series in reverse order using the same do-while logic.