Multiple Choice

  1. What type of loop should we use to request 10 numbers from the user as input?

  2. What type of loop is depicted below?

    Type of Loop ?

  3. How do we call the part int i = 0 in the code snippet below?

     for (int i = 0; i < 10; i++) {
       System.out.println("Hello");
     }
  4. You wish to generate random numbers until you reach a number that is divisible by 9. What type of loop statement would your require for this?

  5. What is the output of the following code snippet?

     for (int i = 0; i < 10; i+=3) {
       System.out.println(i + " ");
     }
  6. This is a(n) ...

     while (true) {
       // Do something
     }
  7. To what does the output of this code snippet refer?

     for (int i = 1; i < 8; i++) {
       if (i % 7 == 0) {
         System.out.print(" ... Ba");
       } else {
         System.out.print("NaN");
       }
     }
     if (5 * 5 >= 25) {
       System.out.print("tm");
     }
     System.out.println("an");
  8. What is the last value of i that will be outputted to the terminal?

     int i = 0;
     do {
         System.out.println("i = " + i);
         i += 5;
     } while (i < 88);
  9. In which of the situations below could you use a for-each loop?

  10. Which construct is preferred in the following situation?

    I wish to read a file line by line and stop at the first line that starts with the word "The".

  11. What is the output of the following piece of code?

    int i = 0;
    System.out.println("i = " + i + " before for loop");
    for (; i < 3; i++) {
      System.out.println(i + ": Hello");
    }
    System.out.println("i = " + i + " after for loop");
    i = 0 before for loop
    0: Hello
    1: Hello
    2: Hello
    i = 3 after for loop
    i = 0 before for loop
    0: Hello
    1: Hello
    2: Hello
    i = 2 after for loop
    i = 0 before for loop
    0: Hello
    1: Hello
    2: Hello
    3: Hello
    i = 3 after for loop
  12. What is the problem with the code below (you can safely assume that the necessary imports are made)?

    public static void main(String[] args) {
      Scanner console = new Scanner(System.in);
    
      for (int i = 0; i < 5; i++) {
        System.out.print("Please enter number: ");
        int number = console.nextInt();
        sum += number;
      }
    
      System.out.println("\nTotal = " + sum);
    }
  13. What construction is depicted below?

    Unknown Construct

  14. Take the code construct below as a reference. In what order are the different parts of a for-loop executed/evaluated?

    for (<Initialization>; <Condition>; <Increment>) {
      // <Code block>
    }
    (1) Initialization
    (2) Condition
    (3) Code block
    (4) Increment
    (1) Initialization
    (2) Code block
    (3) Increment
    (4) Condition
    (1) Initialization
    (2) Condition
    (3) Increment
    (4) Code block
    (1) Initialization
    (2) Increment
    (3) Code block
    (4) Condition

Last updated