Rewrite the following program segment using a for loop. int a = 5, b = 10; while(b > 0) { b -= 2; } System.out.println(a * b);
Topic: Converting while to for
Answer
int a = 5, b; for(b = 10; b > 0; b -= 2) { } System.out.println(a * b);
A for loop gathers the three parts of a loop into one header: for(initialisation; condition; update). Map them across from the while version: initialisation - b = 10, taken from the declaration condition - b > 0, copied unchanged update - b -= 2, moved out of the body into the header Because the body held nothing but the update, the for loop body is left empty. Note that b must still be declared before the loop if you want to use it in the println afterwards — a variable declared inside the for header (for(int b = 10; ...)) would go out of scope when the loop ends, and the print statement would not compile. That scope point is exactly what such a question tests.