Section 5.12 Check Point Questions4 questions
5.12.1
What is the keyword break for? What is the keyword continue for? Will the following programs terminate? If so, give the output.
(a) int balance = 10; while (true) { if (balance < 9) break; balance = balance - 9; } System.out.println("Balance is " + balance); (b) int balance = 10; while (true) { if (balance < 9) continue; balance = balance - 9; } System.out.println("Balance is " + balance);
5.12.2
The for loop in (a) is converted into the while loop in (b). What is wrong? Correct it.
(a) int sum = 0; for (int i = 0; i < 4; i++) { if (i % 3 == 0) continue; sum += i; } (b) int i = 0, sum = 0; while (i < 4) { if (i % 3 == 0) continue; sum += i; i++; }
5.12.3
Rewrite the programs TestBreak and TestContinue in LiveExamples 5.12 and 5.13 without using break and continue.
5.12.4
After the break statement in (a) is executed in the following loop, which statement is executed? Show the output. After the continue statement in (b) is executed in the following loop, which statement is executed? Show the output.
(a) for (int i = 1; i < 4; i++) { for (int j = 1; j < 4; j++) { if (i * j > 2) break; System.out.println(i * j); } System.out.println(i); } (b) for (int i = 1; i < 4; i++) { for (int j = 1; j < 4; j++) { if (i * j > 2) continue; System.out.println(i * j); } System.out.println(i); }