Loops

Why Loops?

Loops are an essential and beginner-friendly aspect of iteration in programming. To iterate means to repeat a process until an outcome is produced. So when do we use iteration in programming, besides in foreach loops for collections?

While Loops

While loops have 2 fundamental pieces: a statement with a Boolean value and a block of code to be executed. We give a while loop to evaluate this conditional statement, and while the statement is FALSE, the loop will run everything we wrote in the block of code underneath. The set up looks like this:

var condition: Boolean = true
while (condition == true) {
  // do stuff
  // eventually condition should change to false
}

Once the statement we’ve given the while loop is false in value, the loop stops itself. In this case, condition == true will evaluate to FALSE when the condition we created earlier isn’t true. Keep in mind that a loop can run infinitely if we write it poorly, so make sure that your condition is manipulated in some way in your for loop to ensure that it will end eventually.

Here’s a good example of a while loop to start with:

var incrementer: Int = 0
while (incrementer < 10) {
  print("$incrementer ")
  incrementer++ // same as incrementer = incrementer + 1
}

We create a variable called incrementer and initialize it to 0. Next, we run a while loop that checks if the incrementer is less than 10 repetitively. While it is less than 10, the block underneath increments incrementer until it equals 10. The following prints out to the console as a result:

0 1 2 3 4 5 6 7 8 9

do...while loops work in the same way, except the block of code is run before the statement is evaluated.

var incrementer: Int = 0
do {
  print("$incrementer ")
  incrementer++
} while (incrementer < 10)

The console will print the same output in this case.

For with Range

To iterate over a range of values, we can use a for loop using the in function. Here’s an example:

for (i in 0..5) println(i)

This prints out the following:

0
1
2
3
4
5

The range is INCLUSIVE, which means that i starts at 0 and ends at 5.

To iterate backwards, we add on the downTo keyword:

for (i in 3 downTo 1 step 1) print("$i ")

The console prints out 3 2 1 as a result. The step keyword indicates the amount incremented or decremented every time. We can modify the step value as well:

for (i in 10 downTo 1 step 2) print("$i ")

This will print 10 8 6 4 2 to the console.

See More

Comments