Learn Objective-C: Loop Aids
In a loop, you can use the keywords continue;
and break;
to control the execution of the loop.
The continue
Keyword
In a loop, continue
tells the program to begin the next iteration, ignoring any code that comes after it. For example, if we had a simple program that reads in input and checks if the input is 5
, we could use the following code:
for (int times = 1; times <= 10; times++) {
int input;
scanf("%d", &input);
if (input != 5)
continue;
NSLog(@"Five!");
}
In this loop, if the input is not 5
, then the word “Five” is not printed. The program moves on to the next iteration of the loop.
The break
Keyword
The break
statement is used in the same context as continue, except that the break statement immediately ends the execution of the loop and moves on to the code after the loop. For example:
for (int times = 1; times <= 10; times++) {
int input;
scanf("%d", &input);
if (input != 5)
break;
}
NSLog(@"Not Five!");
“Not Five” will be printed as soon as the user enters something that is not five.
Pitfalls
Keep in mind that continue and break only apply to the “closest” loop—that is, in the case of nested loops, they will only apply to the “deepest” loop.
This post is part of the Learn Objective-C in 24 Days course.
Previous Lesson | Next Lesson |