Note: C++ programing In mathematics, the factorial of a non-negative integer n,
ID: 3673253 • Letter: N
Question
Note: C++ programing
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 5! = 5x4x3x2x1 = 120. Make a program that asks the user for a positive number, and then prints the factorial of it. In this problem you are required to write a function that calculates the factorial of a positive number, then use this function in your program. You must implement your function by using for loop. You need to check for invalid data (negative number), and ask for another data, until user enter a valid one. Your output should be like following picture:Explanation / Answer
#include<iostream>
#include<cstdio>
using namespace std;
int main() {
int n;
cout << "Enter a number to know its factorial:";
cin >> n;
int fact = 1;
if (n < 0) {
cout << "You entered a negative number" << endl
<< "Please enter a positive integer";
} else if (n == 0)
cout << n << "!=0";
else {
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
cout << n << "!=" << fact;
}
return 0;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.