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.

----*
---***
--*****
-*******
*********
dlysen: I have a dream too! It’s about making a difference within me and to help others to do the same. That’s the kind of dream that gets better the more people you share with it. And I found a whole bunch of people who share the same dream, and that kind of makes us like a family. Follow me on Google+
Related Post