Skip to content
Advertisement

How the output is upto 4 when there is a condition is less than(<)4?

my output is coming along with 4 why

public class whileProgram {
public static void main(String[] args) {
    int counter = 0;
    while(counter<4){
        counter = counter+1;
        System.out.println(counter);
    }
}

}

    Output:
    1 2 3 4

Advertisement

Answer

I think the other answer is not exactly explaining the ‘why’. Here is my attempt at that part of the question.

Consider the code:

while(counter<4){
    counter = counter+1;
    System.out.println(counter);
}

We start with counter equal to 0. 0 is less than 4, so we enter the loop body. Here we first increment counter to 1, and secondly print it. So we print 1.

Now we do it again. 1 is less than 4, so we enter the loop body, increment to 2, and print 2.

Now we do it again. 2 is less than 4, so we enter the loop body, increment to 3, and print 3.

This next time is the important one for the ‘why’ question. counter is now 3, and we are re-evaluating the ‘while’ condition. 3 is less than 4, so we enter the loop body. We increment counter to 4. Then we execute the print statement, so print 4. And that’s the explanation.

The key to understanding this is the sequential execution of statements. You need to mentally follow the execution, as I did in this answer.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement