Alejandro Escamilla macbook

How to print triangle shape asterisk using for loop?

 


This is my first exercises on computer programming 2. To triangle shape asterisk or echo out triangle asterisk in a for loop sequence.

----*
---***
--*****
-*******
*********

Analyzing the output?

It could be 5 line break and so on
The number sequence of the asterisk is x = x+2

Here is the code for the number sequence.

$s=""; // initial variable
$b=9; // base number of the triangle
// execute loop if true
for($i=1;$i< =$b;$i+=2){
// make a line break
$s.=$i."
";
}
echo $s;

The output number sequences we get from the for loop

1
3
5
7
9

We already got the number of asterisk on each row.
Now we can print the asterisk accordingly.

$s=""; // initial variable
$b=9; // base number of the triangle
// execute loop if true
for($i=1;$i< =$b;$i+=2){
// store the string value of $s while the asterisk count is true
for($j=0;$j<$i;$j++){
$s .="*";
}
// make a line break
$s.=$i."
";
}
echo $s;

The output of triangle asterisk using for loop.

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

We add dash to indent the asterisk to center for the final code.

$s=""; // initial variable
$b=9; // base number of the triangle
// execute loop if true
for($i=1;$i< =$b;$i+=2){
// store and add dash on the string value of $s while it is true
// or $k is less than $b-$i
for ($k=0;$k<($b-$i); $k+=2){
$s .="-";
}
// store the string value of $s while the asterisk count is true
// or $j less than $i
for($j=0;$j<$i;$j++){
$s .="*";
}
// make a line break
$s.=$i."
";
}
echo $s;

The output of triangle asterisk using for loop with indention.

----*
---***
--*****
-*******
*********
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.