While loops and for loops: Correct Solution


Part 1

Consider the following code:

A
B
while (C) {
    D
    if (E) {
        F
        G
        break;
    }
    H
}
I
J
  1. Assume the loop breaks on iteration 1. Write out the the order in which the statements will execute.

  2. Assume the loop breaks on iteration 3. Write out the the order in which the statements will execute.

Solution

  1. Order:

    A B C D E I J
  2. Order:

    A B C D E F G H C D E F G H C D E I J

Part 2

Translate the following natural language description of a loop into a for loop:

Declare a variable named we of type long, initialized to a. Then, until we is less than or equal to toca, increment we.

Solution

for (long we = a; we < toca; we++) {
    ...
}

Something to double-check in your solution:


Related puzzles: