Php star triangle
Solved
capa57
Posted messages
383
Status
Member
-
ADil Ou7 -
ADil Ou7 -
Hello,
I want to create a triangle using the character * with a loop based on a number given in a variable $size (example with 5 here)
*
**
***
****
*****
I want to create a triangle using the character * with a loop based on a number given in a variable $size (example with 5 here)
*
**
***
****
*****
Configuration: Windows XP Internet Explorer 6.0
15 answers
-
Well, I don't see where you're getting stuck, apart from the fact that I don't see you using it afterwards, but I'm not judging. However, you mentioned a loop.
If you thought about that, I don't see what your problem is. The implementation is quite simple.
- You define a variable size (number of stars) if you want the generation to be dynamic (controlled by a form, for example).
- You create a loop from 1 to $size that increments by 1 each time (for the rows).
- You place $size number of stars on each line based on $size, so you will have to create another loop from 1 to $size again for the number of stars (echo '*';)
And in the end, you will have your triangle.
That's the basic idea (a very, very French draft algorithm, lol).
Now it's up to you to continue. -
we have the right to do
nb = number of times
star = *
echo nb X "star" -
Euh no, it'll give you an error
you can't multiply an int variable with a string variable ^^'
it would be useful though -
$size = 5;
for ($i = 0; $i < $size; $i++)
echo "* ";
I'm stuck here -
You forgot a loop
The first loop will be used to create the 5 lines 5lines -> 5stars
The second loop will create the correct number of stars
Basically, you redo the same loop, but this time you will put your character '*',
without forgetting the {} around each loop ^^ -
I tried that but it doesn't work
$size = 5;
for ($i = 0; $i < $size; $i++)
echo "*". "
";
for ($i = 0; $i < $size; $i++)
echo "*"; -
I told you not to forget the { and }, if it's not in your code that's normal
$size = 5; for ($i = 1; $i <= $size; $i++) { for ($j = 1; $j <= $size; $j++) { echo "*"; } }
so the logic isn't really there ....
- your loops from 1 to 5 because you have 1 star and you want 5 and not 0 to 4
- don't forget the braces otherwise your loops are useless
- make sure to place your echo '*'; correctly -
-
Hello
I doubt it will work much better :)
If your inner loop uses the same variable as the outer loop, your outer loop is useless
If both go up to $taille, you will always draw 5 stars....
$taille = 5; for ($i = 1; $i <= $taille; $i++) { for ($k = 1; $k <= $i; $k++) { echo "*"; } } -
Oops... forgot the line break every time...
size = 5; for ($i = 1; $i <= $size; $i++) { for ($k = 1; $k <= $i; $k++) { echo "*"; } echo '
'; } -
it gives me that: ***************
I don't understand anything anymore -
-
ah yes, shit, I forgot that one...
a mistake of intention
mark as resolved, bye. -
-