Advertisements

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.

Advertisements
Leave a comment

1 Comment

  1. Learn Objective-C in 24 Days « Programming for iOS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Advertisements
  • 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 222 other followers

  • Back to the Past

    December 2010
    S M T W T F S
    « Nov   Jan »
     1234
    567891011
    12131415161718
    19202122232425
    262728293031  
  • Time Machine

  • You count!

    • 621,662 views
  • Worldwide Stats

    free counters
  • Advertisements
%d bloggers like this: