C - Break & Continue
The break and continue statements are used to control the flow of loops. They allow you to alter the normal execution of a loop based on certain conditions.
Break statement:
The break statement is used to immediately terminate the execution of a loop and exit the loop block. When encountered, it causes the program to jump to the statement immediately following the loop. The break statement is typically used to exit a loop prematurely based on a certain condition. It is commonly used with the if statement to conditionally break out of a loop.
for (int i = 1; i <= 10; i++)
{
if (i == 5)
break;
printf("%d ", i);
}
In this example, the loop iterates from 1 to 10. When i becomes 5, the break statement is encountered, and the loop is terminated. As a result, only the numbers 1, 2, 3, and 4 are printed.
Continue statement:
The continue statement is used to skip the rest of the code block within a loop for the current iteration and proceed to the next iteration. When encountered, it causes the program to jump to the loop's control expression or the increment/decrement statement. The continue statement is typically used to skip specific iterations based on a certain condition, allowing the loop to continue with the next iteration.
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
continue;
printf("%d ", i);
}
In this example, the loop iterates from 1 to 10. When i is an even number, the continue statement is encountered, and the rest of the code block is skipped for that iteration. As a result, only the odd numbers 1, 3, 5, 7, and 9 are printed.