Tongat
Tongat

Reputation: 141

Print pattern of increasing asterisks and zeros

How to print this Pattern?

pattern

$number = 5;
for ($i=1; $i <= $number ; $i++) { 
    for ($j=$i; $j >= 1;$j--){
        echo "0";
    }
    echo "\n";
}

Prints

0
00
000
0000
00000

I've tries like this, but i'm confused to print star and Zero char

for ($i=1; $i <= $number ; $i++) { 
    $sum = 0;
    for ($j=$i; $j >= 1;$j--){
        $sum +=$j;
    }
    echo $i ." => " .$sum ."\n";
}

Prints

1 => 1
2 => 3
3 => 6
4 => 10
5 => 15

Upvotes: 10

Views: 1465

Answers (4)

GDR
GDR

Reputation: 1

$line = '';

for ($i = 1; $i <= 5; $i++) {

   $line = str_repeat('*', $i) . $line . '0'; // **str_repeat()** --> getting string length

   echo $line . PHP_EOL; // **PHP_EOL** ---> represents the endline character.

}

Upvotes: 0

Nick
Nick

Reputation: 147216

You can use str_repeat to generate the strings of required length. Note that for triangular numbers (1, 3, 6, 10, 15, ...) you can generate the i'th number as i(i+1)/2:

$number = 5;
for ($i = 1; $i <= $number; $i++) {
    echo str_repeat('*', $i * ($i + 1) /2) . str_repeat('0', $i) . PHP_EOL;
}

Output:

*0
***00
******000
**********0000
***************00000

Demo on 3v4l.org

For a more literal generation of the triangular part of the output (i.e. sum of the numbers from 1 to i), you could use this code which adds $i *'s and 1 0 to the output on each iteration:

$line = '';
$number = 5;
for ($i = 1; $i <= $number; $i++) {
    $line = str_repeat('*', $i) . $line . '0';
    echo $line . PHP_EOL;
}

Output:

*0
***00
******000
**********0000
***************00000

Demo on 3v4l.org

Upvotes: 17

Parto
Parto

Reputation: 168

The number of zeros are equal to $i in the for loop. So we just need to calculate the number of stars and then simply do a str_repeat

$count = 5;

for ($i=1; $i <= $count; $i++) {

  $stars = 0;
  for($j=1; $j <= $i; $j++) {
    $stars = $stars + $j;
  }

  echo str_repeat('*', $stars).str_repeat('0', $i)."\n";
}

Output:

*0
***00
******000
**********0000
***************00000

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522471

Here is another way, which uses a more literal reading of the replacement logic. Here, I form each subsequent line by taking the previous line, and adding the line number amount of * to the * section, and then just tag on a new trailing zero.

$line = "*0";
$max = 5;
$counter = 1;

do {
    echo $line . "\n";
    $line = preg_replace("/(\*+)/", "\\1" . str_repeat("*", ++$counter), $line) . "0";
} while ($counter <= $max);

This prints:

*0
***00
******000
**********0000
***************00000

Upvotes: 3

Related Questions