Algorithm
1. Start
2. Read input integer 'n'
3. If n is negative:
a. Print an error message: "Error! Factorial of a negative number doesn't exist."
b. Exit
4. Initialize a variable 'factorial' to 1
5. For i from 1 to n:
a. Multiply 'factorial' by i
b. (Repeat for each value of i)
6. Print the calculated factorial value
7. End
Code Examples
#1 Code Example-C++ programing Find the Factorial of a Given Number
Code -
C++ Programming
#include <iostream>
using namespace std;
int main() {
int n;
long factorial = 1.0;
cout << "Enter a positive integer: ";
cin >> n;
if (n < 0)
cout << "Error! Factorial of a negative number doesn't exist.";
else {
for(int i = 1; i <= n; ++i) {
factorial *= i;
}
cout << "Factorial of " << n << " = " << factorial;
}
return 0;
}
Copy The Code &
Try With Live Editor
Output
Enter a positive integer: 4
Factorial of 4 = 24
Factorial of 4 = 24
Demonstration
C++ programing Find the Factorial of a Given Number- DevsEnv