Search code examples
javaloopswhile-loopconditional-statementsstatements

Why does the output change so drastically just because of the change in location of the statement in the while loop?


Well, while trying to understand the total concept of the while loop, I came across this..

public static void main (String[] args) {

    int x = 1;
    System.out.println("Before the loop");

    while(x < 4) {
        x = x + 1;
        System.out.println("In the loop");
        System.out.println("Value of loop x is " + x);
    }

    System.out.println("This is after the loop");

}

Here the output was

Before the loop
In the loop
Value of loop x is 2
In the loop
Value of loop x is 3
In the loop
Value of loop x is 4
This is after the loop

When I changed the position of the statement like this,

    public static void main (String[] args) {

    int x = 1;
    System.out.println("Before the loop");

    while(x < 4) {
        System.out.println("In the loop");
        System.out.println("Value of loop x is " + x);
        x = x + 1;
    }

    System.out.println("This is after the loop");

}

The output was,

Before the loop
In the loop
Value of loop x is 1
In the loop
Value of loop x is 2
In the loop
Value of loop x is 3
This is after the loop

Please explain to me why the output changes so drastically just by changing the location of that one statement.

Any help would be appreciated... I'm a learner aiming high ;)


Solution

  • You have essentially this:

    x = 1
    x = x + 1 // X=2
    print x   // X=2
    --> and then to next loop
    

    and

    x = 1
    print x    // X=1 
    x = x + 1  // X=2
    --> and then to next loop
    

    So, that's really not drastic change, it's +1 to the values, because you do it before the printing vs after the printing