phppattern-matching

Hackerrank draw a staircase of length N in php


Draw a staircase of height N like this:

     #
    ##
   ###
  ####
 #####
######

Staircase of height 6, note the last line should have zero spaces.

My solution does not work correctly

function draw($size)
{
    for ($i = 1; $i <=$size ; $i++)
    {
        $spaces = $size-$i;
        while ($spaces)
        {
            echo " ";
            $spaces--;
        }
        $stairs = 0;
        while ($stairs < $i)
        {
            echo "#";
            $stairs++;
        }
        echo "<br/>";
    }
}
draw(6);
//output
#
##
###
####
#####
######

It is not printing the spaces, I tried \n, PHP.EOL still it didn't work. Any suggestions?


Solution

  • Although other solutions are all good , here is my code as well.

    $max=5;
    for ( $i =1 ; $i<=$max;$i++) {
            for ( $space = 1; $space <= ($max-$i);$space++) {
                    echo " ";
            }
            for ( $hash = 1; $hash <= $i;$hash ++ ) {
                    echo "#";
            }
            echo "\n";
    }