< Previous | Contents | Next >

Introducing the Finicky Counter

Program

The Finicky Counter program counts from 1 to 10 through a while loop. Its finicky because it doesnt like the number 5it skips it. Figure 2.8 shows a run of the program.

You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 2 folder; the filename is finicky_counter.cpp.

Using break and continue Statements 59


image

Figure 2.8

The number 5 is skipped with a continue statement, and the loop ends with a break statement.


// Finicky Counter

// Demonstrates break and continue statements #include <iostream>

using namespace std;


int main()

{

int count = 0; while (true)

{

count += 1;


//end loop if count is greater than 10 if (count > 10)

{

break;

}

60 Chapter 2 n Truth, Branching, and the Game Loop: Guess My Number


//skip the number 5 if (count == 5)

{

continue;

}


cout << count << endl;

}


return 0;

}