Performing Loops


For the rest of this chapter, you’ll see how to perform loops in Visual C++. You’ll also see how to perform unconditional jumps in a loop by using the break and continue statements.

Visual C++ has three loop constructs: the while loop, the for loop, and the do- while loop. Let’s look at the while loop first.

Using while Loops

The following illustration shows a simple while loop.

The following example shows how to write a simple while loop in Visual C++:

int count = 1; while (count <= 5) { Console::WriteLine(count * count); count++; } Console::WriteLine(S"The end");

The while keyword is followed by a conditional expression enclosed in parentheses. (The parentheses are mandatory.) If the conditional expression evaluates to true, the while body is executed. After the loop body has been executed, control returns to the while statement and the conditional expression is tested again. This sequence continues until the test evaluates to false.

Tip

Remember to include some kind of update statement in the loop so that the loop will terminate eventually. The update statement in the preceding example is count++, which increments the loop counter. If you don’t provide an update statement, the loop will iterate forever.

The preceding example displays the output in the following graphic.

click to expand

In this exercise, you will enhance your Calendar Assistant application so that the user can enter five dates.

  1. Continue working with the project from the previous exercise.

  2. Modify the code in the _tmain function to enable the user to enter five dates.

    Console::WriteLine(S"Welcome to your calendar assistant"); int count = 1; // Declare and initialize the loop counter while (count <= 5) // Test the loop counter { Console::Write(S"\nPlease enter a date "); Console::WriteLine(count); int year = GetYear(); int month = GetMonth(); int day = GetDay(year, month); DisplayDate(year, month, day); count++; // Increment the loop counter } 
  3. Build and run the program. The program prompts you to enter the first date. After you have entered this date, the program prompts you to enter the second date. This process continues until you have entered five dates, at which point the program closes.

    click to expand

Using for Loops

The for loop is an alternative to the while loop. The flowchart in the following illustration shows a simple for loop.

The following example shows how to write a simple for loop in Visual C++. This example has exactly the same effect as the while loop you saw earlier.

for (int count = 1; count <= 5; count++) { Console::WriteLine(count * count); } Console::WriteLine(S"The end"); 

The parentheses after the for keyword contain three expressions separated by semicolons. The first expression performs loop initialization, such as setting loop counters. (The initialization expression is performed only once, at the start of the loop.)

Note

You can declare loop variables in the first expression of the for statement. The preceding example illustrates this technique. The count variable is local to the for statement and goes out of scope when the loop terminates.

The second expression in the for statement defines a test. If the test evaluates to true, the loop body is executed. After the loop body has been executed, the final expression in the for statement is executed; this expression performs loop update operations, such as incrementing loop counters.

Note

The for statement is very flexible. You can omit any of the three expressions in the for construct as long as you retain the semicolon separators. You can even omit all three expressions, as in for( ; ; ), which represents an infinite loop.

The preceding example displays the output shown in the following graphic.

click to expand

In this exercise, you will modify your Calendar Assistant application so that it uses a for loop rather than a while loop to obtain five dates from the user.

  1. Continue working with the project from the previous exercise.

  2. Modify the code in the _tmain function to use a for loop rather than a while loop, as shown here:

    Console::WriteLine(S"Welcome to your calendar assistant"); for (int count = 1; count <= 5; count++) { Console::Write(S"\nPlease enter date "); Console::WriteLine(count); int year = GetYear(); int month = GetMonth(); int day = GetDay(year, month); DisplayDate(year, month, day); }

    Notice that there is no count++ statement after display the date because the for statement takes care of incrementing the loop counter.

  3. Build and run the program. The program asks you to enter five dates, as before.

Using do-while Loops

The third and final loop construct in Visual C++ is the do-while loop. The do- while loop is fundamentally different from the while loop and the for loop because the test comes at the end of the loop body, which means that the loop body is always executed at least once in a do-while loop.

The following illustration shows a simple do-while loop.

The following example shows how to write a simple do-while loop in Visual C++. This example generates random numbers between 1 and 6 inclusive to simulate a die, and counts how many throws are needed to get a 6.

Random * r = new Random(); int randomNumber; int throws = 0; do { randomNumber = r->Next(1, 7); Console::WriteLine(randomNumber); throws++; } while (randomNumber != 6);      Console::Write(S"You took "); Console::Write(throws); Console::WriteLine(S" tries to get a 6");

The loop starts with the do keyword, followed by the loop body, followed by the while keyword and the test condition. A semicolon is required after the closing parenthesis of the test condition.

The preceding example displays the output shown in the following graphic.

click to expand

In this exercise, you will modify your Calendar Assistant application so that it performs input validation, which is a typical use of the do-while loop.

  1. Continue working with the project from the previous exercise.

  2. Modify the GetMonth function as follows so that it forces the user to enter a valid month:

    int GetMonth() { int month = 0; do { Console::Write(S"Month [1 to 12]? "); String * input = Console::ReadLine(); month = input->ToInt32(0); } while (month < 1 || month > 12); return month; }
  3. Modify the GetDay function as follows so that it forces the user to enter a valid day:

    int GetDay(int year, int month) { int day = 0; int maxDay; // Calculate maxDay, as before (code not shown here) ... ... ... do { Console::Write(S"Day [1 to "); Console::Write(maxDay); Console::Write(S"]? "); String * input = Console::ReadLine(); day = input->ToInt32(0); } while (day < 1 || day > maxDay); return day; }

  4. Build and run the program.

  5. Try to enter an invalid month. The program keeps asking you to enter another month until you enter a value between 1 and 12, inclusive.

  6. Try to enter an invalid day. The program keeps asking you to enter another day until you enter a valid number (which depends on your chosen year and month).

Performing Unconditional Jumps

Visual C++ provides two keywords—break and continue—that enable you to jump unconditionally within a loop. The break statement causes you to exit the loop immediately. The continue statement abandons the current iteration and goes back to the top of the loop ready for the next iteration.

Note

The break and continue statements can make it difficult to understand the logical flow through a loop. Use break and continue sparingly to avoid complicating your code unnecessarily.

In this exercise, you will modify the main loop in your Calendar Assistant application. You will give the user the chance to break from the loop prematurely, skip the current date and continue on to the next one, or display the current date as normal.

  1. Continue working with the project from the previous exercise.

  2. Modify the _tmain function as follows to enable the user to break or continue if desired:

    Console::WriteLine(S"Welcome to your calendar assistant"); for (int count = 1; count <= 5; count++) { Console::Write(S"\nPlease enter date "); Console::WriteLine(count); int year = GetYear(); int month = GetMonth(); int day = GetDay(year, month); Console::Write(S"Press B (break), C (continue), or "); Console::Write(S"anything else to display date "); String * input = Console::ReadLine(); if (input->Equals(S"B")) { break; } else if (input->Equals(S"C")) { continue; } DisplayDate(year, month, day); }
  3. Build and run the program.

  4. After you have entered the first date, you will be asked whether you want to break or continue. Press X (or any other key except B or C) to display the date as normal.

  5. Enter the second date, and then press C, which causes the continue statement to be executed. The continue statement abandons the current iteration without displaying your date. Instead, you are asked to enter the third date.

  6. Enter the third date, and then press B, which causes the break statement to be executed. The break statement terminates the entire loop.




Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
EAN: N/A
Year: 2003
Pages: 208

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net