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

PHP Class, Object and Methods (Article) Class, Object and Methods (Program)

229

Given Input:

Enter a non-negative integer: 5

Expected Output:


5x4x3x2x1=120

Program:

<?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.


This Particular section is dedicated to Programs only. If you want learn more about PHP. Then you can visit below links to get more depth on this subject.