Course Introduction to Programming

Break and Continue

Course's Page 6 min Text by
User Image
Vitor Hugo Couto

In this lesson, you will learn two commands, continue and break.

To exemplify the commands, we will use the following program as a base, that prints the numbers from 0 to 5.

#include<stdio.h>

int i;
for(int i = 0; i < 6; i++){
	printf("%d\n", i);
}

Continue

The continue command skips the rest of code and jumps to the next iteration (cycle) of a repetition structure.

#include<stdio.h>

int i;
for(int i = 0; i < 6; i++){
	if(i == 2){
		continue;
	}
	printf("%d\n", i);
}

When executing this program, we can notice that the number 2 is not printed. This happens because when is equal to 2, the if is activated and the code inside it, the continue command, is executed, which skips the rest of the code and goes to the next iteration. The printf that was below is ignored, so the number 2 is not printed.

Break

The break command ends a repetition loop.

#include<stdio.h>

int i;
for(int i = 0; i < 6; i++){
	if(i == 2){
		break;
	}
	printf("%d\n", i);
}

In this case, when running the program, we can notice that only the numbers 0 and 1 are printed. This happens because when the counter reaches 2, the if is be activated and the break command is executed, which ends the for loop, not allowing it to print the rest of the numbers.

Now you know how to use continue and break commands to manipulate repeat structures.