﻿ PHP for loops Exercise: Calculate and print the factorial of a number using a for loop - 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:

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:

PHP Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿