Avi Caspe
Avi Caspe

Reputation: 575

Java For Loop Termination Condition: == vs <= vs >=

for (int i = lowerBound; i == upperBound; i++) {
      //Code goes here  
    }

I want the last time the for loop is run to have i equaling upperBound. Is this the right syntax? If so why might one ever use <= or >=? Thanks in advance. :)

Upvotes: 0

Views: 358

Answers (4)

A_G
A_G

Reputation: 1

Use: i <= upperBound inside the loop.

The reason being that the loop is testing against all constraints in that loop and will only run when it ticks these off as being true. i is only equal to upperbound in one case and never while i it is also equal to lowerbound, so it won't run.

(Eek. First ever answer here! I hope this helps!)

Upvotes: 0

Abhinav Gauniyal
Abhinav Gauniyal

Reputation: 7574

for (int i = lowerBound; i == upperBound; i++) {
      //Code goes here  
    }

The part inside for loop executes when it checks the constraint/condition mentioned inside for loop statement.

Example

for( int i =0; i == 10 ; i++){
    saySomething();
}

will run only when i == 10 ie i would have been i=10 , while if you had written i<10 or i<=10 it would have run each time that condition is true.

Here is a quick example : link for for loop.

Upvotes: 1

Aify
Aify

Reputation: 3537

To run all + equals to upperBound, you need to use <=

One may might use >= if you're counting backwards, <= and if you're counting forwards.

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198371

A for loop can always be translated to a while loop as follows:

for(initialization; condition; step) {
   block;
}

To

initialization;
while (condition) {
   block;
   step;
}

So if your condition is i == upperBound, the loop will never run, because the condition doesn't start out as true. <= will do what you want, though.

Upvotes: 3

Related Questions