Loop control statements in C language
Loop control statements are used in C language to alter the normal execution flow of loops.
There are three types of loop control statements in C:
- Break
- Continue
- Goto
Break statement: It is used to abruptly end a loop. When a loop encounters a break statement, the loop is instantly broken, and control is moved to the statement that follows the loop.
Example:
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
printf("%d ", i);
}
// Output: 1 2 3 4
Continue statement: It is used to advance to the subsequent iteration of a loop while skipping the current iteration. When a loop encounters a continue statement, the loop moves on to the next iteration while skipping the statements that follow the continue statement for the current iteration.
Example:
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
printf("%d ", i);
}
// Output: 1 3 5 7 9
Example of for loop:
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
printf("%d ", i);
}
return 0;
}
Goto statement: It is used to provide a labelled statement of authority over the programme. The labelled statement and the goto statement need to be in the same function. Goto is typically avoided since it makes the programme more difficult to read and maintain.
Example:
int i = 1;
loop:
printf("%d ", i);
i++;
if (i <= 10) {
goto loop;
}
// Output: 1 2 3 4 5 6 7 8 9 10
It is important to use these loop control statements judiciously to avoid creating complex and hard-to-understand code.