Opening the reading…
Opening the reading…
PROGRAMMING FUNDAMENTALS › JAVA FUNDAMENTALS
This loop prints the numbers 1, 2, 3, and 4 on separate lines:
for (int count = 1; count <= 4; count++) {
System.out.println(count);
}The three expressions inside the parentheses have different jobs. int count = 1 is the initializer, so count gets its starting value of 1. count <= 4 is the condition, so it decides whether the loop body is allowed to run. count++ is the update, so it changes count after an iteration finishes.
Which clause changes count after each printed line?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The expressions appear on one line, but execution does not repeatedly move from left to right through all three before printing. Java initializes count once, checks the condition, runs the body if the condition is true, performs the update, and then returns to the condition.
count = 1 initialize once
count <= 4 true, so print 1
count++ count becomes 2
count <= 4 true, so print 2
count++ count becomes 3
count <= 4 true, so print 3
count++ count becomes 4
count <= 4 true, so print 4
count++ count becomes 5
count <= 4 false, so leave the loopThe body runs four times, and the condition is checked five times. The fifth check happens after count++ changes count from 4 to 5. Because count <= 4 is then false, the loop exits without printing 5. The initializer is not repeated on those later passes, and the update does not happen before the first print.
In the running loop, count <= 4 includes the boundary value 4. When count is 4, the comparison is true, so the body prints 4. After that print, the update changes count to 5, and the next check fails.
for (int count = 1; count < 4; count++) {
System.out.println(count);
}If you change the condition to count < 4, the body runs for count values 1, 2, and 3. When count becomes 4, count < 4 is false, so the body is skipped and 4 is not printed. The comparison controls which values reach the body, even though the initializer and update stay the same.
The condition was changed to count < 4. Type the comparison that also permits count = 4.
for (int count = 1; count < 4; count++) {
System.out.println(count);
}Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The condition count <= 4 is initially true because count is 1. Each count++ moves count closer to the first value that makes this condition false: 5. That progress lets the loop print 1 through 4 and then stop.
for (int count = 1; count <= 4; ) {
System.out.println(count);
}Without count++, count remains 1 after the body prints it. The next condition check still sees count <= 4 as true, so the body prints 1 again. This repeats forever because neither the initializer nor the condition changes count. The initializer ran before the first check, not before each later body execution, so it cannot restart progress.