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 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);
                        

🖥 Program 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.