Rewrite the following do while program segment using for: x = 10; y = 20; do { x++; y++; } while(x <= 20); System.out.println(x * y);
Topic: Converting do-while to for
Answer
int x, y; for(x = 10, y = 20; x <= 20; x++, y++); System.out.println(x * y);
Map the three parts of the loop into the for header: initialisation - x = 10, y = 20 (the comma operator lets a for header initialise and update two variables at once) condition - x <= 20 update - x++, y++ moved from the body into the header Because the body contained nothing except the two updates, the for loop body is empty — hence the semicolon at the end of the header line. One caution: the original is a do-while, which always runs at least once, whereas a for tests first. Here x starts at 10 and the condition is true immediately, so the two behave identically. Mention that check if the question asks you to justify the conversion.