thinkingincode.ninja [Dark]

Loops

It is very common that a programmer wants to repeat some code a number of times. There are two kinds of loops, each with two variants: for loops, and while loops. The basic idea of a for loop is that you are iterating between some range of values, or across a set of values; while loops are about repeating a block of code only as long as a condition is true.

Within loops, the keywords break and continue have special meaning. break will cause the inner-most loop (because loops can be nested) to be terminated, with code execution resuming at the statement immediately following the loop. continue will cause the remainder of the loop body to be skipped for the current iteration of the loop.

For loops

The classical for loop (so called because it's present in most programming languages and is very commonly seen) consists of four parts: the initializer, the loop condition, the post-iteration statement, and the body of the loop. The intializer is where a variable is declared and given an initial value; this variable has a scope that is limited to the body of the loop, and thus cannot be used either before or after the loop. Usually this variable will be the iterator. The loop condition will be checked prior to each iteration of the loop; if the condition is not met, then the loop will be stopped, and code execution will continue at the next statement following the loop. The post-iteration statement will be executed following each iteration of the loop, and before checking the loop condition. It is generally used to iterate to the next item. Finally, the body of the loop contains the code that will be executed each iteration of the loop. Here is what it looks like, in template form:

for ( <intializer> ; <condition> ; <post-iteration statement> ) {
    <loop body>
}

Say you wanted to add up all the numbers from 1 to 100. You could do it like this:

int sum = 0;
for(int i = 1; i <= 100; i = i + 1) {
    sum = sum + i;
}

Here's how you read it: The loop starts with a variable i being declared, and initialized with a value of 1. Prior to each iteration of the loop (including the first), the computer will check to make sure that i is less than or equal to 100. After each iteration, the value in i will be incremented by 1. In effect, the variable i will have all of the values between and including 1 and 100. In each iteration of the loop, i will have one of those values.

If you wanted to change that to instead add up the sum of each number from 1 to 100 squared, it would be a simple change:

int sum = 0;
for(int i = 1; i <= 100; i = i + 1) {
    sum = sum + (i * i);
}

Say you have an array of Books called BookList, using the Book structure defined in the section on Data Structures, and you want the total number of pages for all Books. Note, the loop condition will cause the loop to terminate once i is equal to the length of the array; this is because, in languages that start array indexing at 0, the last element in the array will be at length - 1. Here, I'm also introducing another code style; not all languages use brackets to designate code blocks (instead using indentation), or require semicolons at the end of each line.

int total_pages = 0
for(int i = 0; i < BookList.length; i += 1)
    total_pages = total_pages + BookList[i].Length

Now let's see some code that finds the index of a Book with a particular ISBN, if one exists. If it does exist, it will break out of the loop early; if there are 1000 books, and it finds a match on book number 23, there's no point in searching through the remaining 977 books. This time I'm using brackets, to make it clear what's going on.

let search_for_ISBN: number = 1234567890
let found_at_index: number
let did_find: boolean = false
for(let i: number = 0; i < BookList.length; i ++)
{
    if(BookList[i].ISBN == search_for_ISBN)
    {
        found_at_index = i
        did_find = true
        break
    }
}

The second kind of for loop is the foreach loop. Not all languages have it, but it's really just syntactic sugar around a regular for loop (syntactic sugar is a term for when the language lets you write something in a simple way which is translated (by the computer) to something more complex). The foreach loop makes it very easy to express iteration across a collection of elements. There are two parts to the foreach loop: the variable you want elements stored in, and the collection you are iterating across. Consider the following, which is a rewrite of the code which sums up the number of pages in a list of books:

int total_pages = 0
foreach(Book book in BookList) {
    total_pages += book.Length
}

While loops

while loops are quite simple: So long as a condition is true, run some code. Thus there's two parts to a while loop: the condition, and the loop body. Here's a while loop that will find the first multiple of 13 that is larger than 100.

int number = 13
while(number <= 100)
    number = number + 13

The other variant of a while loop is the do while loop. It's almost identical to a regular while loop except that the first check of the loop condition is skipped.

int number = 13;
do {
    number = number + 13;
} while(number <= 100);

The do while loop is less frequently seen than the while loop, but it definitely has its use.

Suggested next reading: Comments