How to print this 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
PHP | ImagickDraw line() Function - GeeksforGeeks.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With