For loops

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]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 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] one should write:[/!]

[!java]for (int stepper=0; stepper<n; stepper++) {
    action();
}[/!][!python]for stepper in range(n):
    action()[/!][!scala] for (var stepper <- 1 to n) { 
    action();
}[/!]

This code is then perfectly equivalent to the following one.

[!java]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
}[/!]

The for loop is easier to read, don't you think?

[!java]

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()
}
[/!]

Exercise goal

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.