Grez.Kev
Grez.Kev

Reputation: 277

using scanner input for all for loop parameters

Looking at this code?

import java.util.Scanner;

public class CountingMachineRevisited {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    int from, to, by;
    System.out.print("Count from: ");
    from = scan.nextInt();
    System.out.println("Count to: ");
    to = scan.nextInt();
    System.out.println("Count by: ");
    by = scan.nextInt();

    for (int i = from; i <= to; i+=by) {
        System.out.println(i);
    }

}
}

This code works the way I want it to, but if i change the termination condition of the for loop to i == to, it doesnt work.

for (int i = from; i == to; i+=by) {
        System.out.println(i);
}

I would understand this is all the int's defaulted to 0 making the termination the same as the initial so the for loop would stop, but if I am initializing new values before the loop starts why doesnt it work?

Upvotes: 0

Views: 810

Answers (1)

RealSkeptic
RealSkeptic

Reputation: 34618

The condition in a for loop is not a termination condition. It's a continuation condition.

A for loop like:

for ( INITIALIZATION; CONDITION; UPDATE )
    STATEMENT

Is equivalent to

INITIALIZATION
while ( CONDITION ) {
    STATEMENT
    UPDATE
}

So the loop will continue as long as the condition is true, not terminate when it's true.

So when you input a to that's greater than your from, but put in the condition i == to, since i is initialized to from, and from is different than to, that condition will not be true, hence the loop cannot run - it only runs while it's true.

i <= to works because i starts from a lower value than to, and so this condition is true all the way until i's value surpasses to.

Upvotes: 2

Related Questions