# Need help on reading a nested for loop!

Page 1 of 1

## 2 Replies - 589 Views - Last Post: 05 November 2014 - 04:13 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=357334&amp;s=2fa97debbca6231123d00ae6c89ad9dd&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 lulumars1

• New D.I.C Head

Reputation: 1
• Posts: 8
• Joined: 09-September 14

# Need help on reading a nested for loop!

Posted 05 November 2014 - 02:58 AM

```for (int i = 0; i < 4; i++)
{
for (int k = 0; k < i; k++)
{
System.out.print(" ");
}

for (int j = 4; j > i; j--)
{
System.out.print("\$");
}
System.out.println();
}
```

I was told that the answer when this code segment is printed look's like this:
\$\$\$\$
\$\$\$
\$\$
\$

I'm wondering if someone could help me through the steps of reading this code segment as I'm not getting the expected answer.

Here's what I did:

Looking at the outer for loop, (i) 0 < 4 so I went into the first inner nested loop. (k) 0 is not less than (i) 0 so I went to the 2nd inner nested loop and found that it worked, and I was able to repeat this loop 3 more times and then I exited the loop and printed the line out (giving me the first line of four \$). I then went back to the outer for loop, increased i by 1 and (i) 1 < 4 so I went to the 1st inner nested loop. I used the 0 for the k first and (k) 0 < 1 so I printed out a space (now here's where I get lost) I then incremented k by 1, so k = 1, but 1 is not less than 1 (i) and so I moved on to the next nested for loop. So when this line is printed, I'll only have one space when there should be 4.

Any help on helping me figure out what I did wrong would be great. Thanks in advance!

Lulu

Is This A Good Question/Topic? 0

## Replies To: Need help on reading a nested for loop!

### #2 lulumars1

• New D.I.C Head

Reputation: 1
• Posts: 8
• Joined: 09-September 14

## Re: Need help on reading a nested for loop!

Posted 05 November 2014 - 03:03 AM

Oops! The 2nd, 3rd, and 4th lines of the expected result should have 4 spaces before them

### #3 blackcompe

• D.I.C Lover

Reputation: 1159
• Posts: 2,547
• Joined: 05-May 05

## Re: Need help on reading a nested for loop!

Posted 05 November 2014 - 04:13 AM

@lulumars: You can start by editing your post to reflect what the correct output should look like. Use [CODE] tags if the editor doesn't preserve white space.

This post has been edited by blackcompe: 05 November 2014 - 04:14 AM