-
Nested loops
I'm pretty new to programming and I have an assignment for class that I'm having trouble figuring out how to start.
I have to use nested loops that will cause this to be displayed:
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
I've been trying to figure it out myself, but I can't seem to make any progress. Any tips to help me get started would be appreciated. Thanks.
-
Think of separating the problem into two halves: one for the top half of the triangle and one for the bottom half
-
Two for loops are common. One for the overall figure (how many rows to print), and one nested one inside, to calculate how many digits to print on that row. (what digits to print is dead simple).
for each row i need to print
for each column in the row i am printing
start at zero, and add one
end inside for
end outside for
5 rows above the middle row (0-4) + 5 rows below the middle row, + 1 row (the middle, means you need to print 11 rows total.
Work it out on paper until you see the subtleties of the patterns.
-
I'm still not really getting anywhere. Can you explain any differently/more specific how the 2 for loops would like?
-
Think about obtaining the top section of the triangle, that is:
0
01
012
0123
01234
012345
How would that be accomplished?
Observe that the length of each line is the 1 + the rightmost number. Take the leftmost number on each line as n and the rightmost number on each line as m.
If you were to print the numbers between n and m inclusive, consider how you would use the two variables in order to print each line. (Hint: print n, change its value, repeat until a certain condition is met). So the questions you need to answer are: what value should n be changing to produce each line, and what condition must be met to halt printing on each line.
This process can be done using a single nested for loop inside another for loop.
-
Thanks to both of you. I finally figured it out.