AvP
AvP

Reputation: 359

Why does this while loop act this way?

    int i = 1;
    int j = 1;

    while (i < 4) {

        j += i;

        i++;

    }

    System.out.println("i = " + i);
    System.out.println("j = " + j);

I have the following above and I am trying to figure out how it works. I am new to java so I do not know how to debug my code yet. The output of this program says that i = 4 and j = 7. However the condition of the while loop should only execute when i < 4. Why does it execute when i = 4? I tried changing the condition to i <= 4 and it outputs i = 5. What am I missing here?

Upvotes: 0

Views: 80

Answers (3)

MadConan
MadConan

Reputation: 3767

i = 1

is 1 less than 4? Yes, so loop.

add one to i so now i = 2.

is 2 less than 4? Yes, so loop.

add one to i so now i = 3.

is 3 less than 4? Yes, so loop.

add one to i so now i = 4.

is 4 less than 4? No, leave the loop.

Print the value of i which is 4.

Upvotes: 1

Jack
Jack

Reputation: 2830

You enter the loop when i=3. Inside the loop, you increment i by 1 (i++). At the end of that iteration, you check if i<4, which it is not, because i=4.

Upvotes: 0

TGH
TGH

Reputation: 39278

The loop counter will be incremented for every iteration through the loop. When the counter has been incremented past 3 (when it's equal to 4) the loop will stop. The loop won't run when the counter is 4, but the counter was still incremented to 4

Upvotes: 3

Related Questions