find positive number factorial in C++
To find the factorial of a positive number in C++, you can use a loop to multiply the number by all the positive integers less than it. The factorial of a number n is denoted as n!, and it is the product of all positive integers less than or equal to n.
Here's an example code snippet that calculates the factorial of a positive number in C++:
#include <iostream>
unsigned long long factorial(unsigned int n) {
unsigned long long result = 1;
for (unsigned int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
int main() {
unsigned int num;
std::cout << "Enter a positive integer: ";
std::cin >> num;
std::cout << "Factorial of " << num << " is: " << factorial(num) << std::endl;
return 0;
}
In this code:
1. The factorial
function takes an unsigned integer n
as input and returns an unsigned long long integer, as the factorial of a number can grow very large.
2. Inside the factorial
function, we initialize result
to 1, as the factorial of 0 is defined as 1.
3. We then use a for
loop to iterate from 1 to n
(inclusive) and multiply result
by each number in the range.
4. Finally, we return the result
as the factorial of n
.
5. In the main
function, we prompt the user to enter a positive integer, read it from the standard input using std::cin
, and store it in the num
variable.
6. We then call the factorial
function with num
as the argument and output the result using std::cout
.
Running this code will prompt the user to enter a positive integer, calculate its factorial, and display the result.