C Iteration control - while, do while & for loops Tutorial

In this C tutorial we learn how to repeat sections of code in C with loops. We cover the while loop, the do while loop and the for loop.

We also cover how to nest loops inside each other, how to stop the execution of a loop with break and how to skip to the next iteration of a loop with continue.

What is iteration control and looping

We can repeat sections of code in C to control the flow of our program. This is known as iteration control and we use loops like the while and for loops to achieve iteration control.

As an example, let’s consider an application with a mailing list of users. We would loop through the mailing list, and execute the logic that sends each user a message.

C offers us the following loops to use:

  • while loop
  • do while loop
  • for loop

Let’s take a look at each of these and learn how to use them.

How to use a while loop

A while loop in C will execute a statement repeatedly as long as a condition is true.

Like an if statement, we give the while loop a condition to evaluate. If, and as long as, the condition is true, the code inside the code block will continue to execute.

When something happens that turns the condition to false, the loop will stop executing.

Syntax:
while (condition)
{
	// code to loop
}
Example:
#include <stdio.h>

int main()
{
    int i = 0;

    while (i < 10)
    {
        printf("%d\n", i);
        ++i;
    }

    return 0;
}

In the example above, we initialize a variable called i with the value of 0. The i variable will help us stop the loop when we need to. In this instance it acts as a counter.

In the while loop’s condition, the condition reads: repeat the loop while the value of i is less than 10.

In the code block, we print the value of i to the console to see how the loop iterates. Finally, we increment the value of i by 1.

This is how the code will execute:

  1. Is 0 less than 10?
  2. Yes, print to the console.
  3. set i = i + 1 (0 + 1).
  4. Go back to the beginning of the loop.
  5. Is 1 less than 10?
  6. Yes, print to the console.
  7. set i = i + 1 (1 + 1).
  8. Go back to the beginning of the loop.

This continues until i reaches 10, the compiler sees that i is 10 which is not less than 10 so it stops the loop and moves on to any code below it.

How to use a do while loop

A do while loop is almost the inverse of a while loop.

By that we mean the loop’s execution code will run before the condition is checked. This guarantees that the loop will run at least once.

Syntax:
do
{
	// execution code
}
while (condition);

In a do while statement the code we want to execute is placed inside the do code block. After the do code block we specify the while keyword and the condition.

Something else to note is that a do while statement is terminated with a semicolon. Because we write the while after the curly braces, the compiler needs another way to know where the statement stops.

Example:
#include <stdio.h>

int main()
{
    int i = 0;

    do
    {
        printf("%d\n", i);
        ++i;
    }
    while (i < 10);

    return 0;
}

The example above is the same as the one we used in the while example. When we run the program it will work exactly the same and print the numbers 0 through 9 to the console.

Now let’s see what happens if we change it so that the condition is false the first time the do while loop runs.

Example:
#include <stdio.h>

int main()
{
    int i = 100;

    do
    {
        printf("%d\n", i);
        ++i;
    }
    while (i < 10);

    return 0;
}

In the example above, the condition is false from the start because 100 is not less than 10. When we run the program however, we see that i was printed.

The compiler executed the do block, printing i. Then, it evaluated the while condition to false and stopped the do while loop.

How to use a for loop

A for loop in C will loop a set number of times. A for loop has a built-in, required, counter that’s used to limit the number of times the loop should run.

Because a for loop has a built-in counter, we use it instead of a while loop when we know how many times we want to loop.

Syntax:
for (counter; condition; counter increment)
{
	// code to loop
}

A for loop’s condition is broken up into three sections.

  • the counter setup
  • the condition
  • the counter’s increment

Note that both the counter setup and the condition statements are terminated with a semicolon.

In the section on the while loop we set up our counter outside of the loop. This time we do it as the first part of the conditional statement.

Example:
for (int i = 0; condition; counter increment)
{
	// code to loop
}

Now that we have a counter ready, let’s set up a simple condition.

Example:
for (int i = 0; i < 10; counter increment)
{
	// code to loop
}

The condition would read the same as the while loop: while i is less than 10, execute the code in the code block.

Lastly, we need to increment the counter so that the loop can stop at some point.

Example:
for (int i = 0; i < 10; ++i)
{
	// code to loop
}

It’s like the while loop we created earlier, except everything is inside the parentheses.

Full Example:
#include <stdio.h>

int main()
{
    for (int i = 0; i < 10; ++i)
    {
        printf("%d\n", i);
    }

    return 0;
}

In the example above, we use the for loop to loop through the execution code 10 times.

How to nest loops

C allows us to use loops within other loops, often referred to as nesting.

As an example, let’s consider the popular game Minecraft. The game’s world is made up of identically sized blocks in large stacks, known as chunks .

The chunks are 16 blocks in length, 16 blocks in width and 256 blocks in height. So, a chunk is constructed by looping through each axis and generating the required blocks.

Example:
#include <stdio.h>

int main()
{
    for (int z = 0; z < 256; ++z)
    {
        for (int y = 0; y < 16; ++y)
        {
            for (int x = 0; x < 16; ++x)
            {
                // code to generate visible
                // faces that make up a block
            }
        }
    }

    return 0;
}

In the example above, we need to explain the loop from the inside out.

  • First, we loop 16 times to create a single row of blocks on the x axis.
  • Next, we loop 16 times to create 16 rows of blocks next to each other on the y axis.
  • At this point, we’ve created a 16 x 16 platform of blocks, one block high.
  • Finally, we loop 256 times to create 256 platforms on top of each other.

There’s a lot more logic that goes into the actual creation of a chunk, but the example above is how the nested loop part of it would work.

Now let’s look at the syntax to nest each type of loop.

Syntax: nested while loop
while (outerCondition)
{
	// outer loop code

	while (innerCondition)
	{
		// inner loop code
	}
}
Syntax: nested do while loop
do
{
	// outer loop code

	do
	{
		// inner loop code
	}
	while (innerCondition);
}
while (outerCondition);
Syntax: nested for loop
for (outerCounter; outerCondition; outerCounter increment)
{
	// outer loop code

	for (innerCounter; innerCondition; innerCounter increment)
	{
		// inner loop code
	}
}

Loops aren’t necessarily nested inside their own types, we are allowed to nest a while loop inside a for loop for example.

Something to note is that if we need to nest more than 3 levels deep (like the Minecraft example but deeper), we should consider another approach to the code.

Loop control - How to break out of a loop

In C we can stop the execution of a loop when we need to, and move on to the next section of code outside and below it.

We do this by breaking out of the loop with the break keyword. The break keyword is typically used with a conditional statement like if.

Syntax:
for (counter; condition; counter increment)
{
	// code to loop
	break;
}
Example:
#include <stdio.h>

int main()
{
    for (int i = 0; i < 10; ++i)
    {
        if (i == 5)
        {
            break;
        }

        printf("%d\n", i);
    }

    return 0;
}

In the example above, we loop while our counter is less than 10 and print the counter to the console.

This time however, we added a condition that states if the counter gets to 5, break out of the loop and move on to any code outside and below it.

When we run the example, it only prints up to number 4. When it reaches 5, it stops the loop so 5 never prints.

Loop control - How to skip to the next iteration of a loop

Similar to breaking out of a loop at a certain point, we can skip the current iteration’s execution code.

We skip to the next iteration of the loop with the continue keyword.

Syntax:
for (counter; condition; counter increment)
{
	// code to loop
	continue;
}
Example:
#include <stdio.h>

int main()
{
    for (int i = 0; i < 10; ++i)
    {
        if (i == 5)
        {
            continue;
        }

        printf("%d\n", i);
    }

    return 0;
}

In the example above, instead of breaking out of the loop when the counter gets to 5, we skip the rest of the execution block and move on to the next iteration of the loop.

Summary: Points to remember

  • Loops allow us to control the flow of a program by repeating sections of code.
  • C has three loops. The while loop, the do while loop and the for loop.
  • We use a while loop when we don’t know how many times a loop will run.
  • We use a do while loop when we don’t know how many times a loop will run but it needs to execute at least once.
    • Both a while and a do while loop needs some way to stop, otherwise it could become an infinite loop and crash the program.
  • We use a for loop when we know how many times a loop will run.
    • A for loop has a built-in counter that helps it to stop.
  • Loops can be nested inside one another.
    • If we need to loop more than three times, we should consider a different solution.
  • We stop the iteration cycle of a loop with the break keyword.
  • We skip to the next iteration in a cycle with the continue keyword.