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:
...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.
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 { } .
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:
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:
If the condition is false in the first iteration, then the body will not execute even once.
This construction puts the body before the condition. The only postondition loop in C is the
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:
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 |