Challenge - Factorial Calc
Part of the Fundamentals section of Coddy's PHP journey — lesson 69 of 71.
Challenge
EasyRead one line of input:
- A non-negative integer (e.g.,
5)
Create a function called factorial that accepts one parameter:
$nasint
The function should have a return type declaration of int and calculate the factorial of the given number using a for loop.
The factorial of a number n (written as n!) is the product of all positive integers from 1 to n.
Remember:
- Start with a result of
1 - Multiply the result by each number from
1to$n - The factorial of
0is1
Call the function with the input value and print the returned result.
For example:
5! = 5 × 4 × 3 × 2 × 1 = 120
3! = 3 × 2 × 1 = 6
1! = 1
0! = 1 (by definition)Try it yourself
<?php
// Read input
$n = intval(fgets(STDIN));
// TODO: Create a function called 'factorial' that:
// - Accepts one parameter: $n as int
// - Has a return type declaration of int
// - Uses a for loop to calculate the factorial
// - Returns the result
// Call the function and print the result
echo factorial($n);
?>All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators