Iteration or Loop (while and for)
Iteration, also known as looping, is an important control structure in C language that allows a program to repeat a block of code multiple times. There are three types of loops in C language:
for loop
The for loop is used to execute a block of code a specific number of times.
for (initialization; condition; increment/decrement) {
// code to be executed
}
For example
int i;
for (i = 0; i < 10; i++) {
printf("%d\n", i);
}
while loop
The while loop is used to execute a block of code as long as a certain condition is true.
while (condition) {
// code to be executed
}
For example
int i = 0;
while (i < 10) {
printf("%d\n", i);
i++;
}
do…while loop
The do…while loop is similar to the while loop, but the block of code is executed at least once before the condition is checked.
do {
// code to be executed
} while (condition);
For example
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 10);
Loops can be nested within each other to create more complex programs. It is important to ensure that the loop conditions are properly set up to avoid infinite loops. It is also important to be aware of the resources used by the loop, such as memory and processing power, especially when dealing with large data sets or long-running programs.