Algorithm
-
Input:
- Take an input number (let's call it
n
).
- Take an input number (let's call it
-
Initialization:
- Initialize a variable
factorial
to 1.
- Initialize a variable
-
Loop:
- Use a loop (for or while) to iterate from 1 to
n
.- At each iteration, multiply the current value of
factorial
by the loop variable.
- At each iteration, multiply the current value of
- Use a loop (for or while) to iterate from 1 to
-
Output:
- The final value of
factorial
is the factorial of the input number.
- The final value of
Code Examples
#1 Code Example- Find Factorial
Code -
Javascript Programming
// program to find the factorial of a number
// take input from the user
const number = parseInt(prompt('Enter a positive integer: '));
// checking if number is negative
if (number < 0) {
console.log('Error! Factorial for negative number does not exist.');
}
// if number is 0
else if (number === 0) {
console.log(`The factorial of ${number} is 1.`);
}
// if number is positive
else {
let fact = 1;
for (i = 1; i < = number; i++) {
fact *= i;
}
console.log(`The factorial of ${number} is ${fact}.`);
}
Copy The Code &
Try With Live Editor
Output
Enter a positive integer: 5
The factorial of 5 is 120.
The factorial of 5 is 120.
Demonstration
JavaScript Programing Example to Find the Factorial of a Number-DevsEnv