-
Notifications
You must be signed in to change notification settings - Fork 0
section5_continue_break
In this section we will cover two special keywords to be used in loops: break
and continue
.
Sometimes you don’t want to end a loop, but you want to skip the current iteration and continue with the next. That's possible with the continue
statement. This can be used on three types of loops, for
, while
and do ... while
.
Remember the example for the for
loop where the program displayed numbers from 1 to 10? Imagine that this time you want to display only the odd numbers. A possible solution is to use the continue
statement (though, it's not the best solution).
This is a dummy example where the program asks for user input, integer numbers, and adds 10 numbers. If the input is a negative number, the number is skipped and loop goes to the next iteration.
int i, acc = 0;
for(i = 0; i < 10; i++) {
int input;
scanf("%d", &input);
if(input < 0) continue;
acc += input;
}
printf("Result: %d\n", acc);
This is a dummy example where the program asks for user input, integer numbers, and adds 10 numbers. If the input is a negative number, the number is skipped and loop goes to the next iteration.
The following image illustrates how continue
affects the different loops (Source).
You can also use the break statement
inside loops. This instruction stops the loop immediatly.
Note: break
and continue
statements only affect the loop they belong to.
#include <stdio.h>
int main() {
int n;
printf("Insert a number ? ");
scanf("%d", &n);
// A number is prime if it's divisible only by itself and 1
// for the numbers i, between 2 and 'n'
for(int i = 2; i <= n; i++) // loop A
{
// ... see if there's some 'j', between 2 and 'i'/2 that it's factor of 'i'
int j = 2;
for(; j <= i/2; j++) // loop B
{
if(i % j == 0)
break; // this break only affects the loop B. The loop A will continue
}
if(j > (i/j))
printf("%d is prime!\n", i);
}
}
/*
OUTPUT
Insert a number ? 20
2 is prime!
3 is prime!
5 is prime!
7 is prime!
11 is prime!
13 is prime!
17 is prime!
19 is prime!
*/
Soon...