﻿ PHP Function Exercise: Create a function to calculate the factorial of a positive number - w3resource

# PHP function Exercises: Create a function to calculate the factorial of positive a number

## PHP function: Exercise-1 with Solution

Write a PHP function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.

Visual Presentation:

Sample Solution:

PHP Code:

``````<?php
// Function to calculate the factorial of a number
function factorial_of_a_number(\$n)
{
// Base case: if n is 0, return 1 (factorial of 0 is 1)
if (\$n == 0)
{
return 1;
}
else
{
// Recursive call: calculate factorial by multiplying n with factorial of (n-1)
return \$n * factorial_of_a_number(\$n - 1);
}
}

// Call the function and print the result
print_r(factorial_of_a_number(4) . "\n");
?>
```
```

Output:

```24
```

Explanation:

In the exercise above,

• Define a function named "factorial_of_a_number()" which takes an integer parameter '\$n'.
• Inside the function, there's a conditional check to handle the base case: if the input number '\$n' is 0, the function returns 1, as the factorial of 0 is defined to be 1.
• If the input number is not 0, the function recursively calls itself with the argument '\$n - 1' and multiplies the result with '\$n'.
• The recursive calls continue until the base case is reached (i.e., '\$n' becomes 0), at which point the function returns 1.
• Outside the function definition, the "factorial_of_a_number()" function is called with an argument of 4, which calculates the factorial of 4.
• The result is then printed using "print_r()", followed by a newline character ("\n").

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.

﻿