Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print this pattern using PHP?

Tags:

php

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
like image 392
Tongat Avatar asked Apr 07 '20 06:04

Tongat


People also ask

Which functions are used to draw pattern line in PHP?

PHP | ImagickDraw line() Function - GeeksforGeeks.

What is pattern program?

Pattern programs are nothing but patterns consisting of numbers, alphabets or symbols in a particular form. These kinds of pattern programs can be solved easily using for loop condition.


1 Answers

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

like image 79
Nick Avatar answered Oct 30 '22 00:10

Nick