Introduction to loops in C

This is a short article to introduce you to the concept of loops in C. Once you have an idea of what it is all about, we will go in details for each of them:



Definition

...But first:

    A loop is a construction that allows you to execute a block of code multiple times. It consists of two parts - a condition and a body.

Condition and body

Loop condition

Every loop has a condition. This is the part that controls if the loop should continue or stop. All loops in C continue their iterations if the condition is true. In C, the condition is any valid value or expression that could be evaluated to a value. A value of 0 or '\0' (null) is considered as "false" and everything else is "true"

The body is one or more valid C statements. If it consists of more than one statement, the body must be enclosed in curly brackets { } .

Body

How loops in C work

The loop starts by entering the condition. If it is true the body will be executed. Then the execution repeats the check of the condition and then the body. It looks like this:

    begin -> condition(true)->body-> condition(true)->body ... condition(false)->end.

One check of the condition, followed by one execution of the body is one iteration. Here is a flowchart to visualize the idea:

Flowchart of a precondition loop in programming

Precondition and postcondition loops

Precondition

Precondition, means that the condition of the loop is checked before the body is executed. This is the case with the example above. Such loops is C are:

  • while
  • for

If the condition is false in the first iteration, then the body will not execute even once.

Postcondition

    This construction puts the body before the condition. The only postondition loop in C is the

  • do..while

    Its structure guarantees that the body will be executed at least once, even if the condition is false in the first iteration. Here is a flowchart that visualize:

Flowchart of a post condition loop

In the next lessons, we dive in more details about each loop in C. We will look at their syntax, specifics, usage and many examples. Let's go!

Previous: switch statement

Next: c while loop

   Search this site: