2017-05-14

for ever young – musings about for loops

Welcome to another installment of my series about polyglot madness. Winking smile

Today we will take a look at one way to do things repeatedly. Let’s tart with BASIC yet again.

10 FOR I = 1 TO 3
20 PRINT I
30 NEXT I

The FOR keyword defines both start and end value. Anything that follows until the NEXT keyword is executed repeatedly, in my case, that is just printing a number. Have you noticed the loop variable after NEXT? Most BASIC dialects allow to omit it. In this case the most recent loop is used. Now take a look at this one:

10 FOR I = 1 TO 5 STEP 2
15 FOR J = 1 TO 3
20 PRINT I, J
25 NEXT
30 NEXT

Screenshot of an Oric emulator

The STEP keyword is used to change the increment or decrement value. Before we go back to the future, please note that start, end and increment value are computed prior to the execution of the loop.

Here is how JavaScript handles for loops:

for (i = 1; i <= 3; i++) {
  console.log(i);
}

This surely looks familiar to C, Java and C# developers. There is a nice alternative usage, this time written in Java:

String [] a = {"Java", "C#", "JavaScript", "..."};
  for (String b : a) {
  System.out.println(b);
}

If we translate this into JavaScript, we get something like:

var a = ["Java", "C#", "JavaScript", "..."];
for (var b in a) {
  console.log(b);
}

If we run it, we get… the numbers 0 to 3. Oh my.  In defense of JavaScript I should say that I misused in. The for...in statement is meant to be used to iterate over object properties. To get my above example working as intended, we have to use of instead of in.

Now let’s turn to Swift. Take a look at the following code fragment.

let a = ["Java", "C#", "JavaScript", "..."]
for b in a {
  print(b)
}

This resembles my JavaScript example. But please not the missing paranthesis. To count from 1 to 10 is as simple as:

for b in 1...10 {
  print(b)
}

However, counting down from 10 to 1 has a caveat. Using 10...1, the code will crash. To achieve this, we can use the reversed() instance method:

for b in (1...10).reversed() {
  print(b)
}

Next: Dart:

var a = ["Java", "C#", "JavaScript", "..."];
for (var b in a) {
  print(b);
}

Looks familiar, right? As Dart is greatly influenced by C-like languages, the three-part variant works as well:

for (var i = 1; i <= 10; i++) {
  print(i);
}

That’s it for today. Stay tuned.

No comments:

Post a Comment