How should I set the while loop counter? When is it supposed to be 1 and when is it supposed to be 0?
How should i set a while loop counter? When is it supposed to be 1 and when is it supposed to be 0?
In general, how should I sta开发者_如何学Crt with a while loop problem?
It depends on what you are doing and what you want to accomplish.
If you are iterating through an array, then you will probably want to start your counter with 0
, since arrays are 0
-indexed (the first element of the array is at position 0
). For example:
int integerArray[] = {1, 2, 3}
int counter = 0;
while ( counter < 3 )
{
System.out.println(integerArray[counter]);
++counter;
}
If you are not iterating through an array, it does not really matter what you start your counter with, but it probably does matter how many times you want the loop to iterate. If you want it to iterate 100 times, you could either start with 0
and increment the counter by 1
until counter < 100
, or you could start the counter at 1
and increment it by 1
until counter <= 100
. It's totally up to you. For example:
int counter = 0;
while ( counter < 100 )
{
//prints the numbers 0-99
System.out.println(counter);
++counter;
}
int counter = 1;
while ( counter < 101 )
{
//prints the numbers 1-100
System.out.println(counter);
++counter;
}
Actually, for both of these cases, for
loops would probably serve you better, but the same concept applies:
for (int i = 0; i < 100; ++i)
{
//prints the numbers 0-99
System.out.println(i);
}
A while loop, depending on the language, typically works off a boolean value, not a counter.
while (condition)
{
// Do something until condition == false
}
For "counter" style looping, you'll typically want (again, in most languages) a for loop instead.
精彩评论