Tod Novak
,
Greenhorn
Jun 04, 2008 16:20:00
I'm trying...honestly I am. But maybe some people just aren't cut out to learn programming. I'm really starting to wonder. Anywho... I'm trying to write a small program that will print out a wedge of stars. Seems easy enough. This is what I have so far: Output should be: Initial number of stars: 7 ******* ****** ***** **** *** ** * All I can figure out how to do is print the first line. I know I'm missing something easy, I just can't wrap my head around it.
Henry Wong
,
author
staff
Jun 04, 2008 16:41:00
All I can figure out how to do is print the first line.
Well, your loop only does one line. Can you use a loop to go through all the lines? Basically, have a loop within a loop? Henry
marc weber
,
Sheriff
staff
Jun 04, 2008 16:42:00
You have code that will do something once, and you want it to do that thing multiple times. That's exactly what loops are for. So if you put your code that prints a line inside a loop, then you can print multiple lines.
Garrett Rowe
,
Ranch Hand
Jun 04, 2008 17:17:00
Another way to look at it is to encapsulate what you already know how to do in a method so that you can call it with different parameters. A call to the method might look like: print(7, "*") and the method signature would look like: public void print(int times, String element) once you've got that working (hint hint, you have the code for that one pretty much written) you can work out a loop that calls the method with different arguments: until you're done. To my little brain that's easier to understand than nested loops, as always though, your mileage may vary.
Tod Novak
,
Greenhorn
Jun 04, 2008 17:47:00
Thanks all for the help so far. The lessons I'm following haven't touched on the 'for' loops yet, so I'm kinda stuck with 'if' and 'while' I think. It's the nesting that's causing me such a headache. I'll keep punching it out though.
marc weber
,
Sheriff
staff
Jun 04, 2008 19:31:00
Originally posted by Tod Novak: ...I'm kinda stuck with 'if' and 'while' I think. It's the nesting that's causing me such a headache...
You can do this using nested while loops. The nesting itself is straight forward... But you need to put some thought into what the while conditions are, and the other code that goes inside the loop bodies.
fred rosenberger
,
lowercase baba
staff
Jun 05, 2008 06:46:00
'for' and 'while' loops are really interchangeable. Generally, if you know the exact number of loops, you'd use a 'for', otherwise a 'while', but that's really not written in stone. here's how they would translate: vs
Tod Novak
,
Greenhorn
Jun 05, 2008 09:48:00
Woot! Finally got it! Not sure if it's as pretty as it could be, but it works. Thank you all again for the guidance.
a wee bit from the empire
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com