4.1 | How many times is the following loop body repeated? What is the printout of the loop?
|
4.2 | What are the differences between a while loop and a do-while loop? |
4.3 | Do the following two loops result in the same value in sum ?
|
4.4 | What are the three parts of a for loop control? Write a for loop that prints the numbers from 1 to 100 . |
4.5 | What does the following statement do? for ( ; ; ) { do something; } |
4.6 | If a variable is declared in the for loop control, can it be used after the loop exits? |
4.7 | Can you convert a for loop to a while loop? List the advantages of using for loops. |
4.8 | Convert the following for loop statement to a while loop and to a do-while loop: long sum = ; for ( int i = ; i <= 1000 ; i++) sum = sum + i; |
4.9 | Will the program work if n1 and n2 are replaced by n1 / 2 and n2 / 2 in line 15 in Listing 4.6? |
4.10 | What is the keyword break for? What is the keyword continue for? Will the following program terminate? If so, give the output.
|
4.11 | Can you always convert a while loop into a for loop? Convert the following while loop into a for loop. int i = 1 ; int sum = ; while (sum < 10000 ) { sum = sum + i; i++; } |
4.12 | The for loop on the left is converted into the while loop on the right. What is wrong? Correct it. |
4.13 | Rewrite the programs TestBreak and TestContinue in Listings 4.9 and 4.10 without using break and continue . |
4.14 | After the break outer statement is executed in the following loop, which statement is executed? outer: for ( int i = 1 ; i < 10 ; i++) { inner: for ( int j = 1 ; j < 10 ; j++) { if (i * j > 50 ) break outer; System.out.println(i * j); } } next : |
4.15 | After the continue outer statement is executed in the following loop, which statement is executed? outer: for ( int i = 1 ; i < 10 ; i++) { inner: for ( int j = 1 ; j < 10 ; j++) { if (i * j > 50 ) continue outer; System.out.println(i * j); } } next: |
4.16 | Identify and fix the errors in the following code: 1 public class Test { 2 public void main(String[] args) { 3 for ( int i = ; i < 10 ; i++); 4 sum += i; 5 6 if (i < j); 7 System.out.println(i) 8 else 9 System.out.println(j); 10 11 while (j < 10 ); 12 { 13 j++; 14 }; 15 16 do { 17 j++; 18 } while (j < 10 ) 19 } 20 } |
4.17 | What is wrong with the following program? |
4.18 | Show the output of the following programs: |
4.19 | Reformat the following programs according to the programming style and documentation guidelines proposed in §2.14. Use the next-line brace style. |