Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to calculate 1!+2!+3!+4!+5!

C++ Code Example — Function Programs

ADVERTISEMENT

WAP to calculate 1!+2!+3!+4!+5!

Objective

Write a C++ program to calculate the series sum: 1! + 2! + 3! + 4! + 5!

Algorithm / Approach

  1. Write a recursive fact() function.
  2. In main(), use a for loop from 1 to 5.
  3. Inside the loop, add the result of the function to a running total: sum = sum + fact(i).
  4. Print the sum.
main.cpp
#include<iostream>
using namespace std;
int fact(int);
int main( ){
 int i, sum=0;
 for(i=1; i<=5; i++){
  sum = sum+fact(i);
 }
 cout<<"SUM = "<< 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

  • By placing a function call inside a loop, we can quickly generate complex mathematical series.
  • In this case, the loop counts from 1 to 5, and the function handles calculating the factorial for each individual step.

Complexity

Time Complexity O(n^2) - The loop runs O(n) times, and each factorial calculation takes O(n) time.
Space Complexity O(n) - For the recursive stack.
ADVERTISEMENT