1. Member
Join Date
Feb 2012
Posts
5
Rep Power
0

## Loop Help

Learning loops and was wondering if anyone could help me with the theory here,

public static void main(String[] args)
{

int k=0;
for (int j=0; j<=10; j++) {
if (j == 5)
break;
else
k++;
}
System.out.println(k);
}
}

The answer is k will print 5, but I am just learning loops and don't see how. Would it not go, j=0,k=0,j=1,k=1,j=2,k=2,etc, until j=5 and then k remains at 4? Sorry if this is a silly question or out of place but would appreciate the clarification thanks!

2. ## Re: Loop Help

The best solution would be to step through the code in your head, writing down the value of j and k with each loop. I believe that if you do this, you'll answer you're own question. If not, please feel free to come back and let us know what you've found, or what is still confusing.

Much luck!

3. Member
Join Date
Feb 2012
Posts
5
Rep Power
0

## Re: Loop Help

Hmm ok, does the k++ increase k to 5 in the println?

4. ## Re: Loop Help

Originally Posted by Vingilot
Hmm ok, does the k++ increase k to 5 in the println?
I'm not sure what your question is exactly. The k++ will increase the value of k by 1. The println(k) will print the value of k at that time.

5. Member
Join Date
Feb 2012
Posts
5
Rep Power
0

## Re: Loop Help

Yes, but k++ increases the value when k is next encountered correct? It doesn't increase K at the line k++ but at the next appearance of k?

6. ## Re: Loop Help

Originally Posted by Vingilot
Yes, but k++ increases the value when k is next encountered correct? It doesn't increase K at the line k++ but at the next appearance of k?
No it increments k right there at that spot.

I think I see what your problem is. You're thinking of the difference between ++k and k++, right? Well this difference doesn't matter here at all since either form of this expression will work the same (try it yourself and see). The only time that this matters is when you're using the k at the very same time that you're incrementing it. For e.g.,

Java Code:
```int k = 1;
int foo = k++ + 3; // returns 4

k = 1;
foo = ++k + 3; // returns 5```

7. Member
Join Date
Feb 2012
Posts
5
Rep Power
0

## Re: Loop Help

Ah ok, so it acts the same as ++k, thanks,

8. ## Re: Loop Help

Originally Posted by Vingilot
Ah ok, so it acts the same as ++k, thanks,
You're welcome!

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•