Extension 7: 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.

  • Welcome

    My goal is to make CupsOfCocoa into a beautiful source for beginners to the iPhone platform to get started. Subscribe below for more, and stay tuned!

  • Contact Me

    If you need to contact me for any reason, feel free to send me an email.
  • The Giving Spirit

    If you've found this site helpful, would you consider donating a little sum? Any amount is appreciated...Thanks so much!

  • Roadmap

  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 220 other followers

  • Back to the Past

    May 2020
    S M T W T F S
     12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31  
  • Time Machine

  • You count!

    • 622,650 views
  • Worldwide Stats

    free counters
%d bloggers like this: