While loops and for loops: Correct Solution


Part 1

Translate the following while loop into a for loop:

double bu = pe;
while (bu >= ciIspil) {
    bu--;
    chel();
    mudur(bu);
}

Solution

for (double bu = pe; bu >= ciIspil; bu--) {
    mudur(bu);
    chel();
}

Part 2

Translate the following loop into a for-each loop:

List<Zastri> ipocs;
...
for (int n = 0; n < ipocs.size(); n++) {
    spiTicar(tisti);
    giad(-2, ipocs.get(n), -3);
    pecge();
    oung(ipocs.get(n), 1);
}

Solution

for (Zastri ipoc : ipocs) {
    oung(ipoc.get(i), 1);
    pecge();
    giad(-2, ipoc.get(i), -3);
    spiTicar(tisti);
}

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