FACTORIAL IN C++
Factorial in C++
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int number;
cout << "Enter a positive integer: ";
cin >> number;
cout << "Factorial of " << number << " = " << factorial(number);
return 0;
}
- Include Libraries:
Include the iostream library for input/output operations.
Namespace:
Use the "std" namespace for standard C++ library objects.
Factorial Function:
- Define a recursive function to calculate the factorial of a number.
- If the input is 0 or 1, return 1.
Otherwise, calculate the factorial using recursion.
Main Function:
- Declare a variable "number" to store the input.
- Prompt the user to enter a positive integer.
- Read the input and store it in the "number" variable.
Calculate the factorial using the "factorial" function and display the result.
Return Statement:
- Return 0 to indicate successful execution of the program.