In: Computer Science
In C++ Let n be a non-negative integer. The factorial of n, written n!, is defined by 0 ! 5 1, n! = 1·2·3· · ·n if n $ 1. For example, 4! = 1·2·3·4 = 24. Write a program that prompts the user to enter a nonnegative integer and outputs the factorial of the number. Allow the user to repeat the program. Example: If the user enters a 3 then your program should perform answer = 3 * 2 * 1 = 6. Then 6 will be displayed.
Output: Enter a number: 4
4! = 24
Would you like to try another number? Enter y - yes n
Required Program in C++ -->
#include <iostream>
using namespace std;
int main()
{
int i,fact,number; // declare variables in integer
char another; // declare variable in character
int choice=1; // declare choice and initialize it with 1
while(choice){ // while choice is 1
fact=1; // initialize fact with 1
cout<<"Enter any Number: "; // print enter any number
cin>>number; // read input from user
for(i=1;i<=number;i++){ // for loop will start from i=1 to
i=number
fact=fact*i; // fact is multiplied by i
}
cout<<number<<"! = "<<fact<<endl; // print
number"! = " fact
cout<<"Would you like to try another number"; // ask user if
want to try again ?
cin>>another; // read input from user
if(another == 'Y'|| another =='y'){ //if user enter y or Y
choice=1; // then choice =1, and while loop will continue
}
else if(another =='N'||another =='n'){ // if user enter n or
N
choice=0; // then choice=0, and while loop ends
}
}
return 0;
}