Home / Programs / PHP Program - Write a function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.
Programming Example

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

👁 350 Views
💻 Practical Program
📘 Step by Step Learning

1. PHP Functions Coding Question

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

Case 1: If argument is -3. Output: Invalid input

Case 2: If argument is 5. Output: 5x4x3x2x1=120

Information & Algorithm

Given Input:

Enter a non-negative integer: 5

Expected Output:


5x4x3x2x1=120

Program Code

<?php
 /* Enter your code here. Read input from STDIN. Print output to STDOUT */
 
// Function to calculate the factorial of a number
function factorial($n) {
    if ($n < 0) {
        return "Invalid Argument";
    }
    $result = 1;
    $factorial_string = "";
    for ($i = $n; $i > 0; $i--) {
        $result *= $i;
        $factorial_string .= "$i" . ($i != 1 ? "x" : "");
    }
    return "$factorial_string=$result";
}

// Read user input from standard input
// echo "Enter a non-negative integer: ";
$input = trim(fgets(STDIN));

// Convert user input to integer
$n = intval($input);

// Calculate factorial and print output
echo factorial($n);

Output

Enter a non-negative integer: 5
5x4x3x2x1=120

Explanation

Explanation:

  1. The program now modifies the factorial function to also create a string that represents the factorial calculation.

  2. Inside the for loop, the function appends each number and "x" to the string, except for the last number which is appended without "x".

  3. Finally, the function returns the factorial calculation string and the result in the format "factorial calculation=result".

  4. The program then calls the factorial function with the user input as an argument and prints the output to the console.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.