w3resource
php Programming Exercies

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

PHP function: Exercise-1 with Solution

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

Pictorial Presentation:

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

Sample Solution:

PHP Code:

<?php
function factorial_of_a_number($n)
{
  if($n ==0)
    {
	   return 1;
    }
  else 
    {	
	   return $n * factorial_of_a_number($n-1);
    }
	}
print_r(factorial_of_a_number(4)."\n");
?>

Sample Output:

24

Flowchart :

Flowchart: Create a function to calculate the factorial of positive a number

PHP Code Editor:

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

Previous: PHP Functions Exercises Home.
Next: Write a function to check a number is prime or not.

What is the difficulty level of this exercise?



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