Course: PHP

Progress (0%)

# Exercise: Iterative Factorial

Exercise 6 Easy

Prerequisites for the exercise

## Objective

Create a factorial() function to compute the factorial of a given integer.

## Description

The factorial of an integer $n$ is the product of all integers starting from that integer all the way down to $1$.

In terms of a function, it could be expressed as follows:

$f(n) = n \times (n - 1) \times (n - 2) \times \dots \times 2 \times 1$

For instance:

$1! = 1$
$2! = 2 \times 1 = 2$
$3! = 3 \times 2 \times 1 = 6$
$4! = 4 \times 3 \times 2 \times 1 = 24$
$5! = 5 \times 4 \times 3 \times 2 \times 1 = 120$

$0!$ is a special case — it evaluates to $1$.

In this exercise, you have to create a function factorial() that takes in an integer and returns its factorial.

The function MUST compute the factorial iteratively i.e. using a for (or maybe while) loop. In addition to this, if the given argument to factorial() is not an integer, the function should return the string 'Undefined'.

Shown below are a couple of examples of the function's usage:

<?php

echo factorial(10), "\n";
echo factorial(5), "\n";
echo factorial(2), "\n";
echo factorial(0), "\n";
echo factorial('0'), "\n";
3628800 120 2 1 Undefined

## New file

Inside the directory you created for this course on PHP, create a new folder called Exercise-6-Iterative-Factorial and put the .php solution files for this exercise within it.

## Solution

To start with, let's decide exactly what we need in order to implement the factorial() function:

1. First of all, we need to have single parameter that represents the number whose factorial to compute. Let's call this parameter $n. 2. Secondly, we'll have to use the is_int() function to check whether the passed-in argument is an integer. 3. We'll also need to lay out an if conditional to check for the case when $n is 0 (i.e $0!$) and return 1 in that case.
4. Lastly, we'll need a for loop to iterate as many times as the integer $n and compute the factorial of $n.

And well, this is it.

All this is implemented in the code below:

<?php

function factorial($n) { if (!is_int($n)) {
return 'Undefined';
}

if ($n == 0) { return 1; }$result = 1;
for ($a = 2;$a <= $n;$a++) {
$result *=$a;
}

return $result; } If !is_int($n) returns true, that means that is_int() returned false, which in turn means that the given argument was not an integer, and hence we return 'Undefined'.

Moving on, if $n is 0, we return 1 directly. Finally, if none of these conditions is met, we continue with our factorial computing loop. The for loop iterates $a from 2 up to, and including, the integer $n, and in each iteration multiplies $result with $a. Finally, we return the computed $result.

And this completes our exercise.

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage