While loops and for loops: Correct Solution


Part 1

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

Declare a variable named ce of type int, initialized to nuti. Then, until ce is less than or equal to admio, increment ce.

Solution

for (int ce = nuti; ce < admio; ce++) {
    ...
}

Something to double-check in your solution:


Part 2

Translate the following while loop into a for loop:

int i = 23;
while (i >= sco) {
    i++;
    ruia(i, 1);
}

Solution

for (int i = 23; i >= sco; i++) {
    ruia(i, 1);
}

Part 3

Consider the following code:

A
while (B) {
    C
    D
}
E
  1. Assume the body of the loop executes 1 time. Write out the the order in which the statements will execute.

  2. Assume the body of the loop executes 3 times. Write out the the order in which the statements will execute.

Solution

  1. Order:

    A B C D E
  2. Order:

    A B C D B C D B C D E

Related puzzles: