• Post Reply Bookmark Topic Watch Topic
  • New Topic

Need help with for loop  RSS feed

 
Daniel Ungerfält
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
I made this "lesson" to get the result of a pyramide which I succeded but not understand why im affraid..
The thing is I dont understand exactly how to count it.. Isnt "j" incrementing every loop ?? In my head it should be just one star per line( the height is set to 3)
Can someone please explane how to count from the first loop to the last?
I understand that println change the line though, but not why j would loop more than one time on each line..




for(int i = 1; i <= height; i++){
for(int j = 0; j < i; j++){
System.out.print("*");
}
System.out.println();
}
}
}

result:

*
**
***
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


First off you have 2 extra braces at the every end which is not needed.

If you make a table listing what variables i and j are at each increment you may able to find out what the output is.
given height=3
var i | var j | print *? | println?
1 | 0 | Y | N
1 | 1 | N | Y
2 | 0 | Y | N
2 | 1 | Y | N
2 | 2 | N | Y
3 | 0 | Y | N
3 | 1 | Y | N
3 | 2 | Y | N
3 | 3 | N | Y
 
Daniel Ungerfält
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for helping out mate!
What I can tell from your explanation is that "j" resets to 0 for every new line which "i" dont. Thats what messes with me. Cant really se why. I was countin more like:
var i | var j | print *? | println?
1 | 0 | Y | N
1 | 1 | N | Y
2 | 1 | Y | N
2 | 2 | Y | N
3 | 2 | N | Y
3 | 3 | Y | N


 
Knute Snortum
Sheriff
Posts: 4287
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Daniel Ungerfält wrote:Thanks for helping out mate!
What I can tell from your explanation is that "j" resets to 0 for every new line which "i" dont. Thats what messes with me. Cant really se why.


Every time you iterate over i you start a new for loop with j, so it starts at zero. If you "unroll" the i for loop, if would look like this:

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!