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:
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:
-
The program now modifies the factorial
function to also create a string that represents the factorial calculation.
-
Inside the for
loop, the function appends each number and "x" to the string, except for the last number which is appended without "x".
-
Finally, the function returns the factorial calculation string and the result in the format "factorial calculation=result".
-
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.
5x4x3x2x1=120
Program:
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:
-
The program now modifies the
factorial
function to also create a string that represents the factorial calculation. -
Inside the
for
loop, the function appends each number and "x" to the string, except for the last number which is appended without "x". -
Finally, the function returns the factorial calculation string and the result in the format "factorial calculation=result".
-
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.