120k views
1 vote
A C++ Program that gets a number from the user. If the given number is negative in your input validation loop, you should ask for another number until the user input is a positive value. Then, find the factorial of the given number by a while loop.

Ex:
Please enter a positive number:
User input is -5
Please enter another number:
User input is 4
The program prints, {4! = 24}

User Esabe
by
7.2k points

1 Answer

3 votes

Final answer:

The student's question involves writing a C++ program that validates user input as a positive number and computes its factorial using a while loop. The provided code offers a solution that performs input validation and factorial calculation.

Step-by-step explanation:

The student is asking for C++ programming help to create a program that validates positive user input and calculates the factorial of that number using a while loop. Here is an example of how this could be achieved:

#include
using namespace std;

int main() {
int number, factorial = 1;

cout << "Please enter a positive number: ";
cin >> number;

while (number <= 0) {
cout << "Number is negative. Please enter another number: ";
cin >> number;
}

int counter = number;
while (counter > 1) {
factorial *= counter;
counter--;
}

cout << number << "! = " << factorial << endl;
return 0;
}

This code starts by including the iosteam library for input/output operations and uses the std namespace. The program first prompts the user for a positive number and verifies the input with a while loop. If the input is not positive, the user is repeatedly asked for a positive number. Once a valid number is obtained, another while loop calculates the factorial of that number. The result is then printed out.