Write a factorial program using for loop in php
Description: Write a PHP program to calculate the factorial of a number using a for loop.
Rules and hints:
- Factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
- Use a loop that multiplies the numbers one by one.
PHP program for factorial using a for loop
<?php
$num = 5;
$factorial = 1;
for ($x = $num; $x >= 1; $x--) {
$factorial = $factorial * $x;
}
echo "The factorial of " . $num . " is " . $factorial;
?>
Output:
Tutorials Class - Output Window
The factorial of 5 is 120
How it works
- $factorial starts with 1.
- The loop goes from 5 down to 1, and multiplies $factorial with each number.
- The factorial of 0 is 1, and this program gives 1 for it too, because the loop does not run.
Another way is to use a function that calls itself: factorial using recursion.
Learn more about the similar topics:
| Tutorials |
|---|
| PHP Loops |
| Interview Questions & Answers |
|---|
| No Content Found. |