K-12 CS Teacher Professional Development Workshop
1.) What does this loop output?
for (int i = 0; i < 5) {
System.out.println(i);
}
01234
2.) What does this program output?
boolean om = true;
int i = 0;
for (int u = 0; u > -4; u--) {
while (om) {
if (i == 5) {
om = false;
}
System.out.print(i++);
}
System.out.print(u);
}
a. 012340-1-2-3
b. 0123450-1-2-3
c. 123450-1-2-3
d. 123450-1-2-3-4
e. 12340-1-2-3
The correct answer is b. The inner while loop runs 5 times, and the i++ prints before it is incremented (If we were to have the variable increment before it prints, then it should instead be ++i which would give us 1234560-1-2-3). On the iteration where om becomes false, the statement prints one more time, giving us the 5 in our answer. After this sequence is complete, the while loop can no longer run because om stays false. Thus, the loop simply iterates to print the numbers 0, -1, -2, and -3 before halting because -4 is not less than -4.
3.) What does this program output?
for (int i = 0; i < 10; i++) {
if ( i == 10) {
System.out.print("<");
}
else if (i == 9) {
System.out.print(":");
}
else {
System.out.print("(");
}
}
The output should be (((((((((:
This is because the for loop runs from 0-9, which is 10 total iterations. When i equals 10, the loop ends, so the body of the loop is never executed when i equals 10.