So a couple of months ago, while just discovering the Java language and coding with different functions and whatnot, our teacher introduced the "while" & "for" loops. Of course it seemed pretty simple to understand what these functions did at first but the teacher said that there are a few subtleties that differentiate the two functions.
I remember coding a simple program very recently, and at a certain line, I used the "while" loop so that I could make the program repeat a few operations. So when I ran the program it didn't work... I then replaced the "while" loop with the "for" loop while respecting the coding form, and it worked like magic.
This got me a bit confused, so I was wondering if someone could tell me what the difference between "while" and "for" is?
Robel Bayisa wrote:This got me a bit confused, so I was wondering if someone could tell me what the difference between "while" and "for" is?
Quite a lot. You should probably read Java tutorials on the subject; but what I would say is that there are very few things you can't do with a for loop, but there are several for which a while loop is not suited, so in general I would look at using a for-loop first. Experience will show you when the other forms are more relevant (or easier to read).
Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Well, anything you can do with a while loop can also be done with a for loop. And anything you can do with a for loop can also be done with a while loop. If your while loop didn't work, it's because there was something wrong with the way you'd coded it.
However, they are designed for different cases. Your code is going to be much easier to read if you use them in situations that match that design. And the general rule is:
- If you know in advance how many times you need to iterate, use a for loop
- If you don't know how many times you need to iterate, but you're just going to keep going until some condition is reached, use a while loop
Tto expand on what Matthew B has said already:
A while loop is designed for “sentinel‑controlled” iteration; you keep going until the sentinel value tells you to stop.
A for loop is designed for “counter‑controlled” iteration; you keep going until you reach a particular count.