Saturday, December 4, 2021
HomeTop Coding QuestionWrite a program to print factorial of a number.

Write a program to print factorial of a number.

Given a number we have to calculate the factorial of number .

so what is factorial number?

factorial of a number n is the product of all number from 1 upto the number n.

n!=(n-1)*(n-2)*(n-3)….*1

5!=5*4*3*2*1
=120
3!=3*2*1
=6

Example

input: 5
output:120

input:4:
output:24

Logic:

the logic behind this question is just to multiply all number which are smaller than or equal to them.
#include<iostream>
using namespace std;
int main()
{
 int num;
 cout<<"Enter a number  : "<<endl;
 cin>>num;
 int factorial=1;
 for(int i=1;i<=num;i++)
 {
     factorial=factorial*i;
 }
 cout<<"factorial of a number is "<<factorial<<endl;

}

Output

Enter a number  : 5
factorial of a number is 120

Time complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments