Answer the question
In order to leave comments, you need to log in
How do loops work with an if statement?
I have a small code, can you help me understand why the result will be 7 "YES" entries in the console?
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10;) {
if (i < 5) {
i = i + 1;
}
i = i + 1;
System.out.println("YES");
}
}
Answer the question
In order to leave comments, you need to log in
because the output YES has nothing to do with your if, it is written outside it, then the exit from the loop is determined by the condition in for (the loop will work until i<10), inside the if condition you have an additional increase in i by one, and also at each step in the loop, i increases by 1, which means that the value of i at each step of the loop will be 0,2,4,6,7,8,9 - i.e. 7 times
ps Universal answer - discover debugging, go through your program step by step and look at each step for the values of the variables, comparing them with the expected ones and the behavior.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question