• Trying to understand nested iteration statements
    4 replies, posted
I've been working along in C# quite nicely, but I can't wrap my head around the idea of nested iteration statements. I understand that it's pretty much a loop in a loop, but I can't trace the code of a nested iteration statement and tell you what the output will be. Nor can I do the reverse - writing code to generate a certain output. Here are the three exercises I'm having trouble understanding: [QUOTE]1. Write a program that generates the following output: * ** *** **** ***** ****** ******* ******** 2. Write a program that generates the following output: * ######## ** ####### *** ###### **** ##### ***** #### ****** ### ******* ## ******** # 3. What is the output from the following nested pair of for loops (Trace the source code.)[/QUOTE][PHP]for(int i = 1; i < 4; i++) { for(int j = 1; j < 5; j++) { Console.Write(" {0}", i+j); } }[/PHP]What's the best way to tackle this? How can I better understand this concept? (I've peeked at the answers, but I haven't got any idea WHY they are the answers. I will post them if requested.) Any explanation is appreciated :buddy:
For example that example of yours writes 1+1, 1+2, 1+3, 1+4, 1+5, then starts a new round of the top-level loop, again reseting j to 1. If that's what you were after.
Okay I'm getting a clearer picture...the outer loop represents the number of lines (3 in this case) and the inner represents what will be printed on each of the lines. j increases for each iteration until it reaches 4 (hence four results per line), then we start from the outer loop again... So the second line is 2+1, 2+2, 2+3, 2+4. And the third 3+1, 3+2 and so on... So the output would be 2 3 4 5 3 4 5 6 4 5 6 7 And the answer key confirms my guess :buddy: Okay I've got that much clear, thanks esa. Now for the first two.... :sigh: Well for the first one, there are eight lines. So I'm gonna guess the first line looks like: [PHP]for(int i = 1; i < 9; i ++)[/PHP] And as for the inner loop, I haven't the slightest idea :frown:
The inner loop must be 'dynamic'. Hint: use i in the inner loop declaration.
Even more of a hint: You need to print as many characters as the value of i is. What could you do to print one character for each one in i if you consider i a summmation of the form i = 1 + 1 + &#8230; + 1 Spoiler contains a fairly direct answer, don't read unless you've tried it lots of times. [sp]You would iterate from 1 to i[/sp]
Sorry, you need to Log In to post a reply to this thread.