While loops and for loops: Correct Solution


Part 1

Translate the following while loop into a for loop:

int pe = 70;
while (pe <= raWil) {
    pe /= 4;
    cuas(pe);
}

Solution

for (int pe = 70; pe <= raWil; pe /= 4) {
    cuas(pe);
}

Part 2

Translate the following loop into a for-each loop:

List<SorTiciar> shacs;
...
for (int n = 0; n < shacs.size(); n++) {
    eclo(tiondo, shacs.get(n));
    shacs.get(n).uiss(-1);
    brem();
}

Solution

for (SorTiciar shac : shacs) {
    brem();
    shac.get(i).uiss(-1);
    eclo(tiondo, shac.get(i));
}

It is OK if you gave the variable for the individual collection element (shac) a different name, such as elem. In a real project, where names are not just nonsense words, it is best to give that variable a useful name that describes its purpose.


Related puzzles: