Here we will see how to write a program to find the factorial of a given number.
Basically we find factorial of any number by using its formula. For example 5!=5*4*3*2*1=120.
To write the program we have to follow some steps. So lets see the Algorithm first
Algorithm:
Step 1: Start.
Step 2: Read num.
Step 3: Initialize counter variable i to 1 and fact to 1.
Step 4: if i <=n goto step 5 otherwise goto step 7.
Step 5: Calculate fact = fact * i.
Step 6: Increment counter variable i by 1 and goto step 4.
Step 7: Write fact.
Step 8: Stop.
Program:
/*Factorial of a number*/
#include<iostream>
using namespace std;
int main()
{
int num , fact = 1;
cout<<"Enter a number: ";
//input no. who's factorial you want
cin>>num;
//loop to find factorial
for(int i=1 ; i<=num ; i++)
fact = fact * i ;
cout<<"Factorial of"<<num<<"is:"<<fact;
return 0;
}
Output:
Enter a number: 5
Factorial of 5 is: 120
C++ Program to find factorial
Reviewed by Beast Coder
on
January 15, 2021
Rating:
No comments: