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
CodePudding user response:
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.
CodePudding user response:
Try incrementing counter
after the print line:
class WhileProgram {
public static void main(String[] args) {
int counter = 0;
while (counter < 4) {
System.out.println(counter); // Or System.out.println(counter ); without the next line
counter = counter 1; // Or counter ;
}
}
}
Output:
0
1
2
3
If you only want to print out the numbers 1 through 3 you could also try pre incrementing counter
in the expression for your while-loop:
class WhileProgram {
public static void main(String[] args) {
int counter = 0;
while ( counter < 4) {
System.out.println(counter);
}
}
}
Output:
1
2
3