Loops#

To repeat some commands, loops can be used.

While-Loops#

A while-loop takes a condition, and runs the code inside it as long as the condition is true. When it returns false, the loop stops.

stdout.printf ("Please type in the magic character:\n")

while (stdin.getc () != 'v') {
    stdout.printf ("Wrong Password!\n");
}

stdout.printf ("That was right!\n");

This example reads repeatedly an input from the user, and checks if it is a V. If yes, the loop is stopped and the program prints out that it was the right password. If not, it asks again.

For-Loops#

For repeating a fixed amount of times, for-loops can be used:

for (int i = 0; i < 5; i++) {
    stdout.printf ("%d\n", i);
}

This loop runs the code inside it 5 times.

A for-loop has three fields, seperated by a ;, where you put code into.

The first is executed once when at the beginning of the loop. In this case a new variable named i is defined: int i = 0

After that you must specify a condition which shows if the loop should continue to run another time or stop. Here i < 5 means, that the loop will run, as long as the variable i is smaller than 5. When it turns 5, the loop ends.

The last one specifies the command, that is executed every time when the loop runs another time: i++ So the variable i is always increased, until it reaches 5, when the loop stops.

The output will look like this:

0
1
2
3
4

Of course for-loops are very flexible and you can put whatever you want in them. So it isn’t strictly for fixed amount of repititions.

Do-While-Loop#

This type of loop is very similar to a while-loop, except that the code inside of it is first run without condition, and only after that there is the condition checked:

int number;

stdout.printf ("Guess a number:\n");

do {
    i++;
    stdin.scanf ("%d\n", &number);
} while (number != 278);

stdout.printf ("You got the right number!\n");

The program here asks again and again for a number the user has to type in. If the number is the expected one, the loop quits and there is a nice message printed out. If not, it asks again. The important part here is that the program asks the user at least one time for the number.

Special Keywords for Loops#

There are some commands that you can use inside of loops.

  • The break; keyword lets the loop stop immediately and jumps to its end.

  • continue; skips the rest of the code in the block of the loop and starts the next run of the loop.

Also useful#

  • If you don’t need a field in a for-loop, it can be simply left out:

    int i = 0;
    for (;i < 10;) {
        i++;
        stdout.printf ("%d\n");
    }
    
  • With Arrays you can use a special form of loop called foreach.