1.5k views
5 votes
Write a program that lets the user enter a nonnegative integer and then uses a loop to calculate the factorial of that number. Print the factorial to standard output

User Marivel
by
3.7k points

1 Answer

7 votes

Answer:

In C++:

#include <iostream>

using namespace std;

int main(){

int num,fact=1;

cout<<"Positive integer: ";

cin>>num;

if(num<0){

cout<<"Positive integers only";

}

else{

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

fact*=i;

}

cout<<num<<"! = "<<fact;

}

return 0;

}

Step-by-step explanation:

This line declares num and fact as integer. It also initializes fact to 1

int num,fact=1;

This line prompts the user for a positive integer

cout<<"Positive integer: ";

This line gets input from user

cin>>num;

This line checks if input is negative

if(num<0){

If input is negative, This line prints the following message

cout<<"Positive integers only";

}

else{

If input is positive or 0; The following iteration calculates the factorial

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

fact*=i;

}

This prints the calculated factorial

cout<<num<<"! = "<<fact;

}

User Metin Atalay
by
3.6k points