0

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?

5
  • When i gets the value from, it is not equal to to so the loop is never executed. Try your program with from equal to to and you will see that it will enter the for loop just once. Commented Sep 6, 2015 at 18:05
  • Well what are you initializing your variables to? Depending on your variables, i+by might just jump over the value of to Commented Sep 6, 2015 at 18:06
  • If i initialize them : from = 1, to = 10, by = 2. The loop wont run at all if the termination condition is "i == to". I realize the loop will get messed up if the inputs aren't properly entered. I am curious to why it never executes. Commented Sep 6, 2015 at 18:10
  • @Grez.Kev look at my comment to understand why. Look also at Oracle tutorial on for loop here: docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html Commented Sep 6, 2015 at 18:13
  • I get it now. I am starting with a false statement so it never executes. Thanks Tunaki Commented Sep 6, 2015 at 18:16

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the thorough explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.