Petar Ivanovic
Petar Ivanovic

Reputation: 53

How can I map out a series of characters into an upside-down pyramid using a loop?

I have a task of mapping out this:

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

(notice the spacing), by using a loop(preferably for loop), for a set number of n. example above: $n=5;

This is my latest attempt:

$n=5;
for ($i=0; $i < $n ; $i++) { 

 for ($j=0; $j <= $i ; $j++) { 
     echo "&nbsp;";
 }

 for ($k=0; $k < $n ; $k++) { 
    echo " * ";
 }
 echo "<br>";
}

I want to add something that can reduce n, like n--;, and then print out 1 less "*".

Upvotes: 1

Views: 98

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 79024

Just start at the maximum number of stars and decrement the counter. The maximum minus the current number will give the number of leading spaces needed:

$n = 5;
for($i=$n; $i>0; $i--) {
    echo str_repeat(' ' , $n-$i) . str_repeat('* ', $i) . PHP_EOL;
}

I use str_repeat, you can use a loop if you want. Also, to render in HTML replace the spaces with &nbsp; and PHP_EOL with <br />:

$n = 5;
for($i=$n; $i>0; $i--) {
    echo str_repeat('&nbsp;' , $n-$i) . str_repeat('*&nbsp;', $i) . '<br />';
}

Upvotes: 2

Nigel Ren
Nigel Ren

Reputation: 57141

This builds the longest line by repeating * for the number your after. It also sets a padding to "" to start. Then each loop it just adds an extra space to the padding and takes the last 2 characters off the output line (using substr())...

$n = 5;
$output = str_repeat("* ", $n);
$pad = "";
for ( $i = 0; $i < $n; $i++ )   {
    echo $pad.$output.PHP_EOL;
    $pad .= " ";
    $output = substr($output, 0, -2);
}

gives (note this is in ascii and not HTML)...

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

to use HTML, change the PHP_EOL to <br> and the space to &nbsp;

Upvotes: 1

THess
THess

Reputation: 1007

This should theoretically work:

$space = 0;
$stars = 5;

for($i = 0; $i < 5;$i++){
    echo str_repeat(" ",$space);
    echo str_repeat("* ",$stars);
    $space++;
    $stars--;
    echo PHP_EOL;
}

Output:

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

Upvotes: 1

Related Questions