w3resource
php Programming Exercies

PHP for loop Exercises: Calculate and print the factorial of a number using a for loop

PHP for loop: Exercise-5 with Solution

Write a program to calculate and print the factorial of a number using a for loop. The factorial of a number is the product of all integers up to and including that number, so the factorial of 4 is 4*3*2*1= 24.

Pictorial Presentation:

PHP for loop Exercises: Calculate and print the factorial of a number using a for loop

Sample Solution:

PHP Code:

<?php
$n = 6;
$x = 1;
for($i=1;$i<=$n-1;$i++)
{
 $x*=($i+1); 
}
echo "The factorial of  $n = $x"."\n";
?>

Sample Output:

The factorial of  6 = 720

Flowchart:

Flowchart: Calculate and print the factorial of a number using a for loop

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Create a script to construct the specific pattern, using a nested for loop.
Next: Write a program which will give you all of the potential combinations of a two-digit decimal combination, printed in a comma delimited format.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming