w3resource

PHP for loop Exercises: Construct a specific pattern, using nested for loop


3. Construct Incremental Star Pattern

Create a script to construct the following pattern, using nested for loop.

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

Visual Presentation:

PHP for loop Exercises: Construct a specific pattern, using nested for loop

Sample Solution:

PHP Code:

<?php
// Outer loop to control the rows
for($x=1;$x<=5;$x++)
{
   // Inner loop to control the columns within each row
   for ($y=1;$y<=$x;$y++)
    {
        // Print a star for each column
	    echo "*";
	    
        // Add a space after each star, except for the last one in the row
	    if($y < $x)
		 {
		   echo " ";
		 }
     }
     
     // Move to the next line after printing each row
     echo "\n";
}
?>

Output:

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

Explanation:

In the exercise above,

  • The code starts with a PHP opening tag <?php.
  • It contains an outer "for" loop that iterates through values from 1 to 5, controlling the rows of the pattern (for($x=1;$x<=5;$x++)).
  • Inside the outer loop, there's an inner "for" loop that iterates through values from 1 to the current value of '$x', controlling the columns within each row (for ($y=1;$y<=$x;$y++)).
  • Within the inner loop, a star ('*') is printed for each column (echo "";).
  • Additionally, a space is printed after each star, except for the last one in the row, to create the triangular pattern (if($y < $x) { echo " "; }).
  • After printing all the stars and spaces for a row, a newline character \n is printed to move to the next row (echo "\n";).
  • This process continues until all rows have been printed.
  • Finally, the PHP code ends with a closing tag ?>.

Flowchart :

Flowchart: Construct a specific pattern, using nested for loop

For more Practice: Solve these Related Problems:

  • Write a PHP script to generate a pattern where each row contains one more star than the previous row, using nested for loops.
  • Write a PHP function to produce a pyramid of stars with 5 rows, ensuring proper spacing between stars.
  • Write a PHP program that builds the star pattern dynamically based on a given input for the number of rows.
  • Write a PHP script that outputs a right-angled triangle of stars and adds line breaks using a nested for loop structure.

Go to:


PREV : Sum Integers 0 to 30.
NEXT : Construct Symmetric Star Pattern.

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.



Follow us on Facebook and Twitter for latest update.