Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to Calculate Factorial of a given Number.

C++ Code Example — Function Programs

ADVERTISEMENT

WAP to Calculate Factorial of a given Number.

Objective

Write a C++ program to calculate the factorial of a number using a User-Defined Function.

Algorithm / Approach

  1. Define a function int fact(int x).
  2. Inside the function, use a loop to calculate the factorial of x and return the result.
  3. In main(), read a number, call fact(), and print the returned value.
main.cpp
#include<iostream>
using namespace std;
int fact(int);

int main(){
 int n,res;
 cout<<"Enter number: ";
 cin>>n;
 res = fact(n);
 cout<<"Factorial : "<< res;
 return 0;
}

int fact(int x){
 int i, f=1;
 for(i=1; i<=x; i++){
  f = f*i;
 }
 return f;
}

Expected Output

Enter a Number : 6
Factorial = 720

Explanation of the Program

  • This program moves the factorial calculation logic out of main() and into a dedicated function.
  • By doing this, whenever we need to calculate a factorial in the future, we can simply call fact(n) instead of rewriting the entire for loop every single time.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT