C Program to calculate 1!+2!+3!+4!+5!
Objective
Write a C program to calculate the sum of a factorial series: 1! + 2! + 3! + 4! + 5!
Algorithm / Approach
- Create a recursive
fact()function. - In
main(), initializesum = 0. - Run a loop
ifrom 1 to 5 (or 7 in the provided code). - Inside the loop, call the function and add to sum:
sum = sum + fact(i). - Print the sum.
main.c
#include<stdio.h>
int fact(int);
int main( ){
int i, sum=0;
for(i=1; i<=7; i++){
sum = sum+fact(i);
}
printf("SUM = %d",sum);
return 0;
}
int fact(int x){
if(x==0 || x==1){
return 1;
}
else{
return x*fact(x-1);
}
}
Expected Output
SUM = 153
Explanation of the Program
- This combines loop iterations with functional recursion.
- The loop handles generating the sequence of numbers (1, 2, 3), and for every single number, the recursive function calculates the factorial and hands it back to the loop to add to the grand total.
Complexity
Time Complexity
O(n^2) - For n loop iterations, factorial takes O(n) time.
Space Complexity
O(n) - Recursion stack depth.