Code
FACTORIAL OF A NUMBER
FACTORIAL OF A NUMBER
ENTER A NUMBER:
Output
PHP program to find the factorial of a number |
The factorial of a number n is defined by the product of all the digits from 1 to n [including 1 and n].
For example,
Note:
- It is denoted by n! and is calculated only for positive integers.
- Factorial of 0 is always 1.
The simplest way to find the factorial of a number is by using a loop.
There are two ways to find factorial in PHP:
- Using loop
- Using recursive method
Logic:
- Take a number.
- Take the descending positive integers.
- Multiply them.
Factorial in PHP
Factorial of 4 using for loop is shown below.
Example:
Output:
Factorial using Form in PHP
Below program shows a form through which you can calculate factorial of any number.
Example:
Output:
Factorial using Recursion in PHP
Factorial of 6 using recursion method is shown.
Example:
Output:
The do while loop[edit | edit source]
The do while loop is similar in syntax and purpose to the while loop. The do/while loop construct moves the test that continues the loop to the end of the code block. The code is executed at least once, and then the condition is tested. For example:
Even though $c is greater than 5, the script will echo "Hi" to the page one time.
PHP's do/while loop is not commonly used.
Example[edit | edit source]
This example will output the factorial of $number
[product of all the numbers from 1 to it].
$number = 5; $factorial = 1; do { $factorial *= $number; $number = $number - 1; } while [$number > 0]; echo $factorial;
120
The continue statement[edit | edit source]
The continue statement causes the current iteration of the loop to end, and continues execution where the condition is checked - if this condition is true, it starts the loop again. For example, in the loop statement:
the statement is not executed when the condition i = 0 is true.
For More Information[edit | edit source]
- PHP Manual: Control Structures: do-while