While loops are well adapted to situations where you want to achieve an
action while a condition stays true, but it is less adapted to achieve a
given action a predetermined amount of time. For example, when we wanted to
move stepAmount
steps backward in a previous exercise, we had to
create a new variable, initialize it, and move backward while incrementing
this variable until it became equal to stepAmount
.
In such situations, for
loops become handy. Their syntax is the
following:
[!java|c]for (initializing; condition; incrementing) { action(); }[/!][!python]for variable in sequence of values: action()[/!][!scala] for (variable <- firstValue to lastValue) { action(); }[/!]
For example to repeat the loop body n
times,
[!python] it is handy to use the instruction range(n)
to generate the sequence n integer value from 0 to n-1.[/!]
[!java|scala|c] one should write:[/!]
[!java]for (int stepper=0; stepper<n; stepper++) { action(); }[/!][!c]int stepper; for (stepper=0; stepper<n; stepper++) { action(); }[/!][!python]for stepper in range(n): action()[/!][!scala] for (stepper <- 1 to n) { action(); }[/!]
This code is then equivalent to the following one from the computer point of view. From the programmer point of view, one form or the other can make the source code easier to read, depending on the situation. You should chose wisely in each situation whether you want to use a for loop or a while loop. Your uttermost goal should remain to keep your code simple and easy to read, to ensure that your day remain pleasant and productive.
[!java|c]int stepper = 0; while (stepper < n) { action(); stepper++; }[/!][!python]stepper=0 while stepper < n: action() stepper = stepper + 1[/!][!scala] var stepper = 1 while (stepper <= n) { action() stepper = stepper + 1 }[/!]
In that case, the for
loop is easier to read, don't you think?
It is possible to build more advanced for loops since any valid instruction can be used as initialization, condition and incrementing instruction. The following example is a bit extreme as there is no need for a loop body to move the buggle forward until it reaches the wall, but it works well: all the work is done in the condition and incrementing instruction.
for (; !isFacingWall() ; forward()) { /* nothing in the loop body */ } /* the buggle now faces a wall */[/!] [!scala]
If you want to nest several loops, you can do it on one line in Scala. This means that the two following chunks are equivalent:
for (stepper1 <- 1 to n) { for (stepper2 <- 1 to m) { actions() } }
for (stepper1 <- 1 to n; stepper2 <- 1 to m) { // Simply separate both loop conditions with a semi-column
actions()
}
[/!]
You now have to redo the same exercise than previously
(move forward until being over a baggle, pick it up, move back to your
original location, drop the baggle), but using a for
loop instead
of a while
loop to move back to the initial location.
Once done, you can proceed to next exercise.