tags:

views:

68

answers:

2

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 start with a while loop problem?

+1  A: 

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.

Reed Copsey
yea of course i do have a loop i just need the counter to know the number of operations or number of loops i have done so far, they're like thousands and they definitely do need a counter.
Dina
+3  A: 

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);
}
Steven Oxley
In fact using a while loop is prone to disaster. If you have any conditional statements inside your while loop you suddenly have several code branches to follow, _all_ which require you update the conditional or face the possibility of an _infinite loop_! I've had trouble with junior programmers writing infinite loops into website code because they used `while` instead of `for` and this was a headache for the system administrators who would find all CPU cores spinning after a while on a large website.
PP