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
- Define a function
int fact(int x). - Inside the function, use a loop to calculate the factorial of
xand return the result. - In
main(), read a number, callfact(), 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 entireforloop every single time.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)