Tutorial 3: Loops


WARNING: All "codes" on this page are pseudo-codes, they are not real codes that will compile. They are just ideas.

Loops are what makes a program valuable. It allows you to make the machine do stuff repetitively. There are 3 basic ways that you can do a loop and they are as follows:

  1. While loop

A while loop will continue until a certain condition is met:

while (condition)
{
    ...
    <statements>
    ...
}

What happens is that the while loop will do the following:

  1. Evaluate condition. If condition is false then stop the loop else continue.
  2. Evaluate statements.
  3. Repeat Step 1.

That is the order of which a while loop processes itself.

  1. Do While loop

A do while loop is almost identical with the while loop with one exception: it always processes the statement at least once before evaluating the condition.

do {
    ...
    <statements>
    ...
} while (condition);

It is equivalent to the following while loop:

...
<statements>
...
while (condition)
{
    ...
    <statements>
    ...
}

This is what happens in the loop:

  1. Evaluate statements.
  2. Evaluate condition. If condition is false then stop the loop else continue.
  3. Evaluate statements.
  4. Repeat Step 2.

The good thing about a do while loop is that it's great for stuff like keep asking for an input until the input is valid. It is also great for stuff that depends on the the existence of the first action.

  1. For loop

This is the all time favorite for most programmers. Programmers utilize a for loop about 90% of the time that they need to use a loop. The reason that a for loop is so popular is that it allows you to do more every loop. It has a built in counter.

for (initialization of counter; condition; counter increment)
{
    ...
    <statements>
    ...
}

It is equivalent to the following code for a while loop:

initialize counter;
while (condition)
{
    ...
    <statements>
    ...
    counter increment;
}

I think that code basically tells you how a for loop works. So basically every for loop can be represented in a while loop... but it just packs more for it's worth, making it that much popular. Here is the sequence of how it happens:

  1. Initialize the counter
  2. Evaluate condition. If condition is false then stop the loop else continue.
  3. Evaluate the statements.
  4. Increment the counter.
  5. Repeat Step 2.