Structured programming paradigms rely on three fundamantal control flows: sequence, selection, and iteration. While selection logic handles decision-making via statements like if and switch, repetitive tasks are managed through iteration constructs. C provides three primary keywords for looping: for, while, and do-while.
The For Loop
Among the iteration tools, the for loop is often the most versatile for counted repetitions. Its syntax consolidates initialization, condition checking, and variable updates into a single line.
for (initialization; condition; update)
{
// loop body
}
The execution flow begins by running the initialization clause exactly once. Next, the condition is evaluated. If the condition evaluates to false (zero), the loop terminates. If true (non-zero), the body executes. After the body completes, the update clause runs, followed by another condition check. This cycle repeats until the condition fails.
Below is an implementation that outputs integers from 1 to 10:
#include <stdio.h>
int main(void)
{
for (int counter = 1; counter <= 10; ++counter)
{
printf("%d ", counter);
}
return 0;
}
Comparing While and For
Both while and for loops manage repetition through initialization, condition testing, and state adjustment. However, the while loop disperses these elements across different lines, whereas the for loop groups them logically.
While Loop Implementation:
#include <stdio.h>
int main(void)
{
int current = 1;
while (current < 11)
{
printf("%d ", current);
++current;
}
return 0;
}
For Loop Implementation:
#include <stdio.h>
int main(void)
{
for (int index = 1; index < 11; ++index)
{
printf("%d ", index);
}
return 0;
}
Because the for statement keeps loop control variables and conditions localized, it generally offers better readability and maintenance, especially when the loop body contains complex logic.
The Do-While Loop
The do-while construct differs significantly from for and while loops regarding when the condition is evaluated.
do
{
// loop body
} while (condition);
Pre-test loops like while and for verify the condition before entering the body. If the condition is initially false, the body never executes. In contrast, do-while is a post-test loop. It executes the body first, then evaluates the condition. Consequently, the code block within a do-while loop is guaranteed to run atleast once.
Here is how to print values from 1 to 10 using this structure:
#include <stdio.h>
int main(void)
{
int value = 1;
do
{
printf("%d ", value);
++value;
} while (value < 11);
return 0;
}