While loops and for loops: Correct Solution


Part 1

Translate the following while loop into a for loop:

double azes = 22;
while (azes <= icSpism) {
    azes /= 4;
    iniIss(azes);
}

Solution

for (double azes = 22; azes <= icSpism; azes /= 4) {
    iniIss(azes);
}

Part 2

Translate the following loop into a for-each loop:

Ussa[] grils;
...
for (int i = 0; i < grils.length; i++) {
    diper(7, grils[i]);
    bencen(-1, grils[i], capec);
    grodeu(cusTrenpo);
}

Solution

for (Ussa gril : grils) {
    grodeu(cusTrenpo);
    bencen(-1, gril.get(i), capec);
    diper(7, gril.get(i));
}

It is OK if you gave the variable for the individual collection element (gril) 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: