Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

1. The Basics > 1.11. Implementing While Loops

1.11. Implementing While Loops

Problem

You want to let a piece of code run over and over again until a certain condition is met.

Solution

Use while loops and specify your exit condition. Here is the format for the while loop:

while (<replaceable>condition</replaceable>){
  CODE
}

Note

As long as the condition is a value other than zero/nil/NULL, the while loop will run.

Discussion

The while loop is the arrogant brother of the for loop (see Recipe 1.10) because while loops only take a condition that should be met for the loop to run. If the condition is positive, the loop will always run until the condition becomes negative. For instance, a while loop could be implemented to make an icon in the Dock in Mac OS X jump up and down until the user taps on that icon (this is actually a very bad user experience; icons in the Dock shouldn’t jump up and down continuously, but for a short interval, or even a fixed number of times, usually 3). The exit condition for the while loop is the user’s tapping on that icon. As long as the user hasn’t tapped on the icon, the icon will jump up and down.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial