Bird
0
0

Which PHP code correctly prints a 3x3 grid of asterisks (*) using nested for loops, with each row on a new line?

hard📝 Application Q8 of 15
PHP - Loops
Which PHP code correctly prints a 3x3 grid of asterisks (*) using nested for loops, with each row on a new line?
Afor ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { echo '*\n'; } }
Bfor ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { echo '*'; } echo "\n"; }
Cfor ($i = 1; $i <= 3; $i++) { echo '*'; for ($j = 1; $j <= 3; $j++) { echo '*'; } }
Dfor ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { echo '* '; } }
Step-by-Step Solution
Solution:
  1. Step 1: Outer loop for rows

    The outer loop runs 3 times, each representing a row.
  2. Step 2: Inner loop for columns

    The inner loop runs 3 times per row, printing '*' without newline.
  3. Step 3: Print newline after each row

    After inner loop finishes, echo "\n"; moves to the next line.
  4. Final Answer:

    for ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { echo '*'; } echo "\n"; } correctly prints a 3x3 grid with rows on new lines.
  5. Quick Check:

    Newline after inner loop completes each row [OK]
Quick Trick: Print newline after inner loop to separate rows [OK]
Common Mistakes:
  • Printing newline inside inner loop
  • Not printing newline at all
  • Incorrect loop boundaries

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes