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

Working with Loops

Although you can use simple for and while loops for straightforward tasks, there are some considerations you should make when using more complicated loops. In the next sections, we’ll look at infinite loops and the break and continue statements, which give you more control over your loops.

Creating an Infinite Loop

The for and while loops give you quite a bit of control over the loop. In some cases, this can cause problems if you’re not careful. For example, look at the following loop code:

while (i < 10) {
    n++;
    values[n] = 0;
}

There’s a mistake in this example. The condition of the while loop refers to the i variable, but that variable doesn’t actually change during the loop. This creates an infinite loop. The loop will continue executing until the user stops it or until it generates an error of some kind.


  

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