Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to calculate 1!+2!+3!+4!+5!

C Code Example — Function Programs

ADVERTISEMENT

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

  1. Create a recursive fact() function.
  2. In main(), initialize sum = 0.
  3. Run a loop i from 1 to 5 (or 7 in the provided code).
  4. Inside the loop, call the function and add to sum: sum = sum + fact(i).
  5. 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.
ADVERTISEMENT