Misplaced Rows In An Asterisk-Built, ASCII-Art Pyramid Made Using Multiple For Loops In PHP

Viewed 128

here is my code i need to fix this pyramid here you can see the display and the code
the problem is that

         *        * *//these i want to fix
       *   *
      *     *
     *       *
    *         *
   *           *
  *             *
 *               *
*                 *
$n = 10;
for ($i = 1; $i <= $n; $i++)
{
    for ($j = 0; $j < ($n - $i); $j++)
        echo " ";
    echo "*";
    for ($j = 1; $j <= $i-1; $j++)
        echo " ";
    for ($k = 1; $k < $i-1; $k++)
        echo " ";
    if($i!=1)
        echo "*</br>";
}

Demo of Broken Code

3 Answers

You have if($i!=1) as a condition within the end of the first $i for loop. This actually needs to be moved to the first, sub-for loop.

Why is this? Well, your $i for loop is printing two *'s. At the top of the pyramid, though, you only have one * symbol. In this case, we need to exclude displaying in that case, but only in that case.

Full Working Demo.

$n = 10;
for ($i = 1; $i <= $n; $i++)
        {
            for ($j = 0; $j < ($n - $i); $j++)
                echo " ";
                if($i!=1) {
                    echo "*";
                }
            for ($j = 1; $j <= $i-1; $j++)
                echo " ";
            for ($k = 1; $k < $i-1; $k++)
                echo " ";
                echo "*\n";
        }

Full output:

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

You had two stray * displaying. The second was caused by cases after $i == 1 being displayed in the first for loop on $i, and the first was caused by not ignoring the * symbol on the first case of $i in the $j for loop.

play for example


<?php
for ($i = 0; $i < 15; $i++) {

    echo str_repeat(' ',15-$i). "*" . str_repeat(' ', 2*$i) . "*\n";
}

echo ' '.str_repeat('*', 31)."\n";

if ($i != 1) is skipping over the new line output when $i is 1, which is why your second "line" is being output on the first line still. If you change the logic around outputting <br> it will work.

$n = 10;
for ($i = 1; $i <= $n; $i++)
{
    for ($j = 0; $j < ($n - $i); $j++) {
        echo " ";
    }
    echo "*";
    for ($j = 1; $j <= $i-1; $j++) {
        echo " ";
    }
    for ($k = 1; $k < $i-1; $k++) {
        echo " ";
    }
    
    if ($i != 1) {
        echo "*";
    }
    echo "<br>";
}
         *
        * *
       *   *
      *     *
     *       *
    *         *
   *           *
  *             *
 *               *
*                 *
Related