# Loop Help

• 02-24-2012, 02:38 AM
Vingilot
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!
• 02-24-2012, 03:15 AM
Fubarable
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!
• 02-24-2012, 03:20 AM
Vingilot
Re: Loop Help
Hmm ok, does the k++ increase k to 5 in the println?
• 02-24-2012, 03:24 AM
Fubarable
Re: Loop Help
Quote:

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.
• 02-24-2012, 03:27 AM
Vingilot
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?
• 02-24-2012, 03:31 AM
Fubarable
Re: Loop Help
Quote:

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.,

Code:

```int k = 1; int foo = k++ + 3; // returns 4 k = 1; foo = ++k + 3; // returns 5```
• 02-24-2012, 03:34 AM
Vingilot
Re: Loop Help
Ah ok, so it acts the same as ++k, thanks,
• 02-24-2012, 04:18 AM
Fubarable
Re: Loop Help
Quote:

Originally Posted by Vingilot
Ah ok, so it acts the same as ++k, thanks,

You're welcome!