0
class ExcerciseLib1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int x = 1;
        while (x < 10) {
            x = x + 1;
            if (x > 3) {
                System.out.println("big x");
            }
            if (x < 4) {
                System.out.println("big 1");
            }

        }

    }

}

In the code above, big 1 get's output 2 times, and big x gets output 7 times. I don't quite understand why big x outputs 7 times, shouldn't it be 6 times?

I get that

if (x < 4) {
                System.out.println("big 1");
            }

outputs "big 1" twice because using the loop,

  1. x = 1 + 1 equals 2 which is less than 4,
  2. x = 2 + 1 equals 3 which is less than 4.

So for

if (x > 3) {
            System.out.println("big x");
        }

Shouldn't the loop only output it 6 times?

  1. x = 3 + 1 equals 4, 4 is greater then 3, so output big x.
  2. x = 4 + 1 equals 5, 5 is greater than 3, so output big x.
  3. x = 5 + 1 equals 6, 6 is greater than 3, so output big x.
  4. x = 6 + 1 equals 7, 7 is greater than 3, so output big x.
  5. x = 7 + 1 equals 8, 8 is greater than 3, so output big x.
  6. x = 8 + 1 equals 9, 9 is greater than 3, so output big x.
  7. x = 9 + 1 equals 10; but the loop states x < 10

I'm getting brain stumped on this one. Am I understanding the "x = x + 1" expression wrong?

1
  • 1
    change into System.out.println(x+",big x"); you'll get answer. Commented May 22, 2014 at 23:13

2 Answers 2

4

The loop condition is only run at the start of each iteration. The loop doesn't magically end partway through if the condition becomes false in the middle of an iteration.

So in the final iteration, x is intially 9, and then you add 1 to make it 10, and the loop continues on.

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

1 Comment

Ohh ok I understand it now. Thanks for the clarity guys!
1

The x < 10 is evaluated before the increment...

so when x == 9, it enters the body of the loop, increments x to 10 then prints the output, then evaluates the conditional again

Comments

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.