w3resource

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.

Visual Presentation:

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

Sample Solution:

PHP Code:

<?php
// Set the value of n to 6
$n = 6;

// Initialize variable x to store the factorial value
$x = 1;

// Loop to calculate the factorial of n
for($i = 1; $i <= $n - 1; $i++)
{
    // Calculate factorial iteratively
    $x *= ($i + 1); 
}

// Print the factorial of n
echo "The factorial of  $n = $x"."\n";
?>

Output:

The factorial of  6 = 720

Explanation:

In the exercise above,

  • The code begins with a PHP opening tag <?php.
  • It sets the variable '$n' to 6, representing the number whose factorial is to be calculated.
  • Another variable '$x' is initialized to 1. This variable stores the factorial value.
  • A "for" loop calculates the factorial. It iterates from 1 to n-1 ($i=1; $i<=$n-1; $i++), as the factorial of 'n' is calculated by multiplying all positive integers up to n.
  • Inside the loop, each iteration multiplies the current value of '$x' by the next integer, starting from 1 up to 'n'.
  • After the loop completes, the calculated factorial value is printed using "echo", along with a message indicating the number whose factorial is calculated ("The factorial of $n = $x").
  • Finally, PHP code ends with a closing tag ?>.

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?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/php-for-loop-exercise-5.php