Factorial of any number n is represented by n! and is equal to 1*2*3*....*(n-1)*n.
Write an algorithm to find the factorial of any given number.
Answers
Answer:
or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. ... C++ program to find factorial of given number ... unsigned int factorial(unsigned int n) .
Explanation:
Algorithm : a
Step 1 : Start.
Start 2 : Read n.
Start 3 : Initialize counter variable i to 1 and fact to 1.
Start 4 : if i <= n go to step 5 otherwise goto step 7.
Start 5 : calculate fact = fact * i.
Start 6 : increment counter variable i and goto step 4.
Start 7 : Write fact.
Start 8 : Stop.
Algorithm:
Step 1: Start
Step 2: Take input from the user in variable n.
Step 3: Declare a variable factorial
Step 4: Initialize factorial = 1
Step 5: Start a loop from i = 1 up to i<=n
Step 6: factorial = factorial * i
Step 7: Loop end
Step 8: Print factorial
Step 9: End
Program in C++
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter a number : ";
cin>>n;
int factorial = 1;
for(int i = 1 ; i <= n ; i++)
{
factorial = factorial * i;
}
cout<<"Factorial of "<<n<<" = "<<factorial;
return 0;
}
Output:
Enter a number : 5
Factorial of 5 = 120