while
loop and a for
loop is about the code’s style and efficiency. It’s not about necessity.Anything that you can do with a for
loop, you can do with a while
loop as well. Consider, for example, this fo
r loop. Here’s how you can achieve the same effect with a while
loop:
<strong>int count = 0;</strong>
while (<strong>count < 10</strong>) {
out.print("I've chewed ");
out.print(count);
out.println(" time(s).");
<strong> count++;</strong>
}
In the while
loop, you have explicit statements to declare, initialize, and increment the count
variable.
The same kind of trick works in reverse. Anything that you can do with a while
loop, you can do with a for
loop as well. But turning certain while
loops into for
loops seems strained and unnatural. Consider this while
loop:
while (total < 21) {
card = myRandom.nextInt(10) + 1;
total += card;
System.out.print(card);
System.out.print(" ");
System.out.println(total);
}
Turning this loop into a for
loop means wasting most of the stuff inside the for
loop’s parentheses:
for ( ; total < 21 ; ) {
card = myRandom.nextInt(10) + 1;
total += card;
System.out.print(card);
System.out.print(" ");
System.out.println(total);
}
The preceding for
loop has a condition, but it has no initialization and no update. That’s okay. Without an initialization, nothing special happens when the computer first enters the for
loop. And without an update, nothing special happens at the end of each iteration. It’s strange, but it works.
Usually, when you write a for
statement, you’re counting how many times to repeat something. But, in truth, you can do just about any kind of repetition with a for
statement.