114k views
3 votes
The factorial of a number n, written in math as n!, is the product of all the numbers from 1 to n or 1*2*3* … *n. Write a C++ program that requests a number from the user and then displays the factorial of that number. The program should only accept positive integers greater than 0.

User ARJUN KP
by
5.5k points

1 Answer

2 votes

Answer:

#include <iostream>

using namespace std;

int main()

{

int factorial=1;

int num;

cout<<"Enter any Number: ";

cin>>num;

for(int i=1;i<=num;i++){

factorial=factorial * i;

}

cout<<"The factorial of the number is "<<factorial<<endl;

return 0;

}

Step-by-step explanation:

Create the main function and declare the variable.

then, print the message by using the cout instruction.

store the value enter by user in the variable.

After that, take a for loop from 1 to user value both are included.

and multiply the value with previous value and it happen until the condition in the loop true.

for example:

i=1

fact = 1*1=1

i=2

fact = 1*2=2

i=3

fact= 2*3=6 and so on....

finally print the result.

User Yalei Du
by
6.3k points