Ad Code

Print star pattern triangle in PHP

In this tutorial you will learn how to print different star pattern triangles in php. These kind of short questions are always asked in interviews, people who solve these problems quickly have a great understanding about loops and 2D/3D dimensional array. The concept can be used to solve the problem in C/C++/Java or any other programming languages just the syntax will differ.

To print a star pattern triangle in PHP – Pattern #1

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

// the length of rows you want
$rows_length = 10;
for ($rows=0; $rows < $rows_length ; $rows++) {
  for($columns = 0; $columns <= $rows; $columns++ ) {
    echo "*";
  }
  echo "<br>";
}

To print a star pattern triangle in PHP – Pattern #2

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

// the length of rows you want
$rows_length = 10; 
for ($rows=$rows_length; $rows > 0 ; $rows--) {
  for($columns = 0; $columns < $rows; $columns++ ) {
    echo "*";
  }
  echo "<br>";
}

To print a star pattern triangle in PHP – Pattern #3

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

// the length of rows you want $rows_length = 10; for ($rows=1; $rows <= $rows_length ; $rows++) { // this loop is for spaces for($columns1 = 0; $columns1 < $rows_length-$rows; $columns1++ ) { echo "&nbsp; "; } // this loop is for stars for($columns2 = 0; $columns2 < $rows; $columns2++ ) { echo "*"; } echo "<br>"; }

To print a star pattern triangle in PHP – Pattern #4

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

// the length of rows you want $rows_length = 10; for ($rows=1; $rows <= $rows_length ; $rows++) { // this loop is for spaces for($columns1 = 1; $columns1 < $rows; $columns1++ ) { echo "&nbsp; "; } // this loop is for stars for($columns2 = 0; $columns2 <= $rows_length - $rows; $columns2++ ) { echo "*"; } echo "<br>"; }

Post a Comment

0 Comments