Course Introduction to Programming
Break and Continue
In this lesson, we will learn about two very important commands that allow us to control the flow of looping structures: Continue and Break.
These commands are useful when we want to skip a part of the code or end a loop earlier than planned, making our programs more dynamic and efficient.
Continue
The continue command is used to skip the rest of the code inside the loop and go directly to the next iteration (that is, to the next repetition cycle). This means that when the program encounters a continue, it ignores all the instructions below it in the current block and returns to the beginning of the loop to check the condition again.
Example
#include<stdio.h>
int i;
for(int i = 0; i < 6; i++){
	if(i == 2){
		continue;
	}
	printf("%d\n", i);
}
/*
Output:
0
1
3
4
5
*/
When executing this program, we notice that the number 2 is not printed. This happens because the moment if's code is executed, and since what is inside this if is the continue command, which goes to the next iteration of the code, the printf that was below is ignored, thus not printing the 2.
Break
The break command is used to completely stop a loop, ending its execution before the condition becomes false. It is very useful when we want to stop a loop upon reaching a specific condition, without needing to go through all the repetitions.
Example
#include<stdio.h>
int i;
for(int i = 0; i < 6; i++){
	if(i == 2){
		break;
	}
	printf("%d\n", i);
}
/*
Output:
0
1
*/
In this case, when executing the program, we notice that only the numbers 0 and 1 are printed. This happens because the moment the counter if will be activated and the break command will be executed, which terminates the for loop, not allowing it to print the rest of the numbers.
Conclusion
Throughout this lesson, you have learned what the continue and break commands are and how they work, understood their differences, and seen practical examples of how each one acts within looping structures. With continue, you can skip certain parts of the code and proceed to the next repetition, while with break, it is possible to end the loop earlier than planned.
Now you know how to use continue and break to control the behavior of looping structures, making your programs smarter and well-structured ๐
