Skip to content

Module 3 Mastery Check

wolvesled edited this page Aug 30, 2013 · 4 revisions
  1. Write a program that read characters from the keyboard until a period is received.
  2. Show the general form of the if-else-if ladder. Answer: if(condition) statement; else if(condition) statement; else if(condition) statement; else statement;
  3. Givenif(x < 10) if(y > 100) { if(!done) x = z; else y = z; } else System.out.println("error"); // what if? to what if does the last else associate? Answer: the second if.
  4. Show the for statement for a loop that counts from 1000 to 0 by -2. Answer: for(int i=1000; i>=0; i--);
  5. Is the following fragment valid? for(int i = 0; i < num; i++) sum += i; count = i; Answer: not valid, variable i is declared inside the for block, which is not able to be used outside.
  6. Explain what break does. Be sure to explain both of its forms. Answer: break skips remaining code in a block and continue with the code after the belonging block. break label skips remaining code in the labeled block and continue with the code following the labeled block.
  7. In the following fragment, after the break statement executes, what is displayed? for(i = 0; i < 10; i++) { while(running) { if(x<y) break; // ... } System.out.println("after while"); } System.out.println("After for"); Answer: ten of "after while" followed by one of "After for".
  8. What does the following fragment print? for(int i = 0; i<10; i++) { System.out.print(i + " "); if((i%2) == 0) continue; System.out.println(); } Answer: 1 3 5 7 9
  9. The iteration expression in a for loop need not always alter the loop control variable by a fixed amount. Instead, the loop control variable can change in any arbitrary way. Using this concept, write a program that uses a for loop to generate and display the progression 1, 2, 4, 8, 16, 32, and so on. Answer: for(int i = 1; ; i += i) System.out.print(i + " ");
  10. The ASCII lowercase letters are separated from the uppercase letters by 32. Thus, to convert a lowercase letter to uppercase, subtract 32 from it. Use this information to write a program that reads characters from the keyboard. Have it convert all lower case letters to upper case, and all uppercase letters to lowercase, displaying the result. Make no changes to any other character. Have the program stop when the user presses period. At the end, have the program display the number of case changes that have taken place.
  11. What is a infinite loop? Answer: a loop with condition always true.
  12. When using a break with a label, must the label be on a block that contains the break? Answer: when need to break control flow and continue after a specified block belonged to. and yes the label on a block must contain the calling break.

Clone this wiki locally