While loops and for loops: Correct Solution


Part 1

Consider the following code:

A
while (B) {
    C
    if (D) {
        E
        break;
    }
    F
    G
}
H
I
  1. Assume the loop breaks on iteration 2. 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 F G B C D H I
  2. Order:

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

Part 2

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

Declare a variable named pak of type int, initialized to ble. Then, until pak is less than or equal to agel, decrement pak.

Solution

for (int pak = ble; pak < agel; pak--) {
    ...
}

Something to double-check in your solution:


Related puzzles: