﻿ PHP for loops Exercise: Print alphabet pattern Q - w3resource

# PHP for loop Exercises: Print alphabet pattern Q

## PHP for loop: Exercise-29 with Solution

Write a PHP program to print alphabet pattern 'Q'.

Visual Presentation:

Sample Solution:

PHP Code:

<?php
for (\$row=0; \$row<7; \$row++)
{
for (\$column=0; \$column<=7; \$column++)
{
if ((\$column == 1 and \$row != 0 and \$row != 6) or (\$row == 0 and \$column > 1 and \$column < 5) or (\$column == 5 and \$row != 0 and \$row != 5) or (\$row == 6 and \$column > 1 and \$column < 4) or (\$column == \$row - 1 and \$row > 3))
echo "*";
else
echo " ";
}
echo "\n";
}
?>

Output:

***
*   *
*   *
*   *
* * *
*  *
** *

Explanation:

In the exercise above,

• The code starts with a PHP opening tag <?php.
• It utilizes a nested loop structure to iterate over rows and columns to create a specific pattern.
• The outer loop (for (\$row=0; \$row<7; \$row++)) controls the rows of the pattern, iterating from 0 to 6.
• Inside the outer loop, there's another loop (for (\$column=0; \$column<=7; \$column++)) that controls the columns, iterating from 0 to 7.
• Within the inner loop, there's a conditional statement that determines whether to print an asterisk ('*') or a space ( ) based on the position of the current row and column indices.
• The condition checks multiple cases:
• If the column is at index 1 and the row is not at index 0 or 6.
• If the row is at index 0 and the column is between indices 1 and 4.
• If the column is at index 5 and the row is not at index 0 or 5.
• If the row is at index 6 and the column is between indices 1 and 3.
• If the column index is equal to the row index minus 1 and the row index is greater than 3.
• If any of these conditions are met, an asterisk ('*') is echoed. Otherwise, a space ( ) is echoed.
• After printing each row, the code moves to the next line by echoing a newline character ('\n').
• Once all rows and columns are printed according to the pattern, the PHP code ends with a closing PHP tag ?>.

Flowchart :

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿