Jessica M.
Jessica M.

Reputation: 1459

While loops and step

init; 
while (test) {
  statements;
  step;
    }

I had a question about the location of the step in the above while loop. Does it matter where the step is written? In other words does it change the any of the values in the while loop if the step is written as the first statement or somewhere in the middle or at the end? If it does can you provide a short example to illustrate that effect.

Upvotes: 2

Views: 314

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

The placement of the step could definitely influence the body of the loop. Imagine if the code below were accessing an array, the first example could miss the first element in an array.

This outputs 0-9

int x = 0;

while(x < 10){
  System.out.println(x);
  x++; 
}

This outputs 1-10

int x = 0;

while(x < 10){
  x++; 
  System.out.println(x);
}

Upvotes: 7

Aurand
Aurand

Reputation: 5537

The step is just another variable. If the statements inside your loop reference it, then yes, it matters. If not, it's position does not matter (as long as it's somewhere in the loop).

Upvotes: 0

Related Questions