Menu
Coddy logo textTech

Challenge - Factorial Calc

Part of the Fundamentals section of Coddy's PHP journey — lesson 69 of 71.

challenge icon

Challenge

Easy

Read one line of input:

  • A non-negative integer (e.g., 5)

Create a function called factorial that accepts one parameter:

  • $n as int

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 1 to $n
  • The factorial of 0 is 1

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