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
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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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 ;)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.