Find Factorial of a Number in PHP using For Loop & Recursion

How to calculate factorial of a number in PHP. In this tutorial, I am going to discuss factorial program in PHP using recursion as well as iterative approach.

Before solving this problem let’s understand what is factorial?

What is Factorial?

Factorial of a non-negative integer n (n!), is the product of all positive integers less than or equal to n.

For example –

5! = 5 * 4 * 3 * 2 * 1 = 120

4! = 4 * 3 * 2 * 1 = 24

Fibonacci series program in PHP

Palindrome program in PHP

Programming Video Tutorials

Program to Print Factorial of a Number in PHP

Program to Print Factorial of a Number in PHP

If you are not familiar with the concept of recursion. Then check my previous tutorial on recursion Vs iteration.

Factorial Program in PHP

Let’s write a function to calculate factorial of a number in PHP. In this code example, I have created a function calculateFactorial which takes a number as an argument and calculate it’s factorial using for loop.

PHP Program to Find Factorial of a Number using Recursion

We have learned, how to calculate factorial of a number using iterative approach. Let’s write a PHP code to calculate factorial of a number using recursion.

Recursion concept with an example

Recursion vs iteration

Explanation

This is how this program is executed.

MCQ on recursion for practice

We can also do the same thing by creating a class.Let’s create a PHP class which calculate and print factorial of a number.

PHP Class to Calculate and Print Factorial of a Number

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.