Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to calculate 1/1!+2/2!+3^2/3!+4^3/4!+5^4/5!+6^5/6!

C++ Code Example — Function Programs

ADVERTISEMENT

WAP to calculate 1/1!+2/2!+3^2/3!+4^3/4!+5^4/5!+6^5/6!

Objective

Write a C++ program to calculate a complex exponential factorial series.

Algorithm / Approach

  1. Define a fact() function and a custom power() function.
  2. Use a loop to calculate the term for each step: power(i, i-1) / fact(i).
  3. Add it to a running float sum.
main.cpp
#include<iostream >
int fact(int);
float power(int,int);
int main( ){
 int i;
 float sum;
 for(i=0; i<=6; i++){
   sum = sum+power(i,i-1)/fact(i);
 }
 cout("Sum = %f\n",sum);
 return 0;
}

int fact(int x){
 if(x==0 || x==1){
  return 1;
 }
 else{
  return x*fact(x-1);
 }
}
float power(int x, int y){
 int j, result=1;
 for(j=1; j<=y; j++){
  result = x*result;
 }
 return result;
}

Expected Output

Sum = 22.174999

Explanation of the Program

  • This program uses multiple separate utility functions (power and factorial) to build a complex mathematical equation cleanly.
  • Note on the provided code: There is a severe syntax error on line 199. cout("Sum = %f\n", sum); is invalid C++. It attempts to mix C-style printf formatting with the C++ cout object. It should either be printf("Sum = %f\n", sum); or cout &lt;&lt; "Sum = " &lt;&lt; sum;.

Complexity

Time Complexity O(n^2)
Space Complexity O(n)

Common Mistakes

  • Syntax Error: Attempting to use printf style formatting inside a cout statement (e.g., cout("Sum = %f", sum)).
ADVERTISEMENT