Why does this work?

• December 15th, 2012, 05:21 PM
Skybear
Why does this work?
I understand how loops and nested loops work. But in the code below, I don't see why one * is printed on the first line, two on the second, etc., instead of just a column of *'s. I'm probably missing something missing very simple. Can someone explain this to me?
-------------

What is the output of the following nested for loops?
Code :

```  for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); }```
Output:
Code :

``` * ** *** **** *****```
• December 15th, 2012, 05:37 PM
pbrockway2
Re: Why does this work?
Are you happy with the difference between print() and println()?

By my count that code should print 20 characters: 15 asterisks and 5 newlines. Walk through the code and make sure you can account for all 20 characters.

---

Don't forget to use "code" tags with your posts. [code]<your code here>[/code].
• December 15th, 2012, 05:41 PM
Skybear
Re: Why does this work?
Oh yes, I understand the difference between print() and println(). But I don't see how there should be 20 asterisks. For example, initially the i=1, so j=1, one asterisk gets printed, and the println statement causes the advancement to the next line. But I'm not sure why the next line has two asterisks and how j++ and i++ play into this.

Sorry about the code tags. I've never added code to this site before.
• December 15th, 2012, 06:19 PM
pbrockway2
Re: Why does this work?

First i is 1. You are right: j is made to go from 1 to 1 (ie from 1 to i). So one asterisk is printed. And then the newline. That completes one pass through the outer loop.

The second verse is the same as the first but with i equal to 2. So j is made to go from 1 to 2 (ie from 1 to i). So two asterisks are printed. And then the newline.

The next time around the outer loop i is 3 and the inner loop will go from 1 to 3, printing an asterisk each time to give 3.

etc.

Key to the behaviour of the code is that in the inner loop j always starts at 1, but is made to increase to a bigger and bigger value each time because i will be bigger each time the inner loop executes.

---

The i++/j++ expressions are there to say how i and j get incremented at the end of the loop. In both cases they are saying that the loops (both of them) increment the loop variable by one.
• December 15th, 2012, 06:34 PM
Skybear
Re: Why does this work?
Of course! Good explanation. I see now that what I was doing was that after i increased to 2, I was reading j = i, when I should have read j<=i, which in essence resets j back to 1 and allows it to increase to 2. Thanks!
• December 16th, 2012, 12:23 AM
pbrockway2
Re: Why does this work?
You're welcome, I'm glad you've got it sorted out.