Jump to content

Star patten using for loop


natsu

Recommended Posts

Spent about 20-30min on this and I am kinda frustrated why I cant get this to work lol. Some help would be appreciated

 

			<?php
				$max = 10;
				for ($row = $max; $row >= 0; $row--) {
					for ($star = 1; $star <= row; $star++) {
						echo "*";
					}
				}
			?>

 

I am trying to get this:

 

**********

*********

********

*******

******

*****

****

***

**

*

Link to comment
https://forums.phpfreaks.com/topic/251316-star-patten-using-for-loop/
Share on other sites

Spent about 20-30min on this and I am kinda frustrated why I cant get this to work lol. Some help would be appreciated

 

Admittedly, not sure why you would want to ... but here you go:

 

<?php
for ($row = 10; $row > 0; $row--) {
	for ($cnt = 0; $cnt < $row; $cnt++) {
		$star .= "*";
	}
	echo $star . "<br />";
	$star = NULL;
}
?>

 

Now, if you want the stars to go the other direction (1-10 instead of 10-1), just flip the direction in which the variables are evaluated.

Why not use the str_repeat function instead?

 

Sure, that works too. I always try to stick to the OP's logic as much as possible - unless it's a blatant syntax violation or they have specifically asked for alternatives. Your suggestion implements the solution in more of a PHP way of doing things while the double loop scenario is more of a language agnostic way of doing things.

 

Admittedly, this is a PHP forum, so one should expect answers to be language biased. Either way, both solutions would work just fine.

Nearly any language with a set of string-specific functions will have a way to repeat a string without the programmer having to deal with loops.

 

I'm not necessarily here to fix code or help someone finish a project quicker. If the OP's logic isn't ideal, I generally suggest something that is or is closer to.

 

Regardless, I agree. I just hope you didn't do his homework for him ;)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.