Number triangle in PHP can be printed using for and foreach loop. There are a lot of patterns in number triangle. Some of them are show here.
Pattern1
<?php $k=1; for($i=0;$i<4;$i++){ for($j=0;$j<=$i;$j++){ echo $k." "; $k++; } echo "<br>"; } ?>
Output:
Pattern 2
<?php $k=1; for($i=0;$i<5;$i++){ for($j=0;$j<=$i;$j++){ if($j%2==0) { $k=0; } else { $k=1; } echo $k." "; } echo "<br>"; } ?>
Pattern 3
<?php for($i=0;$i<=5;$i++){ for($j=1;$j<=$i;$j++){ echo $j; } echo "<br>"; } ?>
Pattern 4
<?php for($i=0;$i>=5;$i++){ for($j=1;$j>=$i;$j++){ echo $i; } echo "<br>"; } ?<
Pattern 5
<?php for($i=0;$i<=5;$i++){ for($j=1;$j<=$i;$j++){ echo "1"; } echo "<br>"; } ?>
Pattern 6
<?php for($i=0;$i<=5;$i++){ for($j=5-$i;$j>=1;$j--){ echo "1"; } echo "<br>"; } ?>
Pattern 7
<?php for($i=0;$i<=5;$i++){ for($j=5-$i;$j>=1;$j--){ echo $j; } echo "<br>"; } ?>
Pattern 8
<?php for($i=5;$i>=1;$i--){ for($j=$i;$j>=1;$j--){ echo $i." "; } echo "<br>"; } ?>
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Pattern1
Output:
Pattern 2
Output:
Pattern 3
Output:
Pattern 4
Output:
Pattern 5
Output:
Pattern 6
Output:
Pattern 7
Output:
Pattern 8
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer