MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Factorial (Loop) with Explanation

PHP Easy PHP Control Flow 29 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around factorial, loop, one. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Given n, print n! using a loop.

Input Format

One integer n.

Output Format

One integer factorial.

Constraints

0

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php $inputText=trim(stream_get_contents(STDIN)); if($inputText==='') exit; $n=intval($inputText); $ans=1; for($i=2;$i<=$n;$i++) $ans*=$i; echo $ans; ?>

Output Example

Input:
5
Output:
120

Common Mistakes

- Starting the loop from 0 (factorial becomes 0).
- Not initializing the factorial value as 1.
- Using int for large n causing overflow.
- Printing extra spaces/newlines that break format.

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next