Home > Sample chapters

Decision and Loop Statements in Microsoft Visual C++

Performing loops

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

C++ has three main loop constructs: the while loop, the for loop, and the do-while loop.

Let’s look at the while loop first.

Using while loops

A while loop continues executing its body for as long as the condition in parentheses evaluates to true. The following example shows how to write a simple while loop in C++/CLI:

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

You must follow the while keyword with a conditional expression enclosed in parentheses. As long as the conditional expression evaluates to true, the while body executes. 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.

You must, of course, remember to include some kind of update statement in the loop so that it will terminate eventually. In this example count++ is incrementing the loop counter. If you don’t provide an update statement, the loop will iterate forever, which probably isn’t what you want.

The preceding example displays the following output:

httpatomoreillycomsourcemspimages1722378.jpg

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

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

  2. Modify the code in the main function by replacing the entire body of the function with the following code:

    Console::WriteLine("Welcome to your calendar assistant");
    
    int count = 1;    // Declare and initialize the loop counter
    while (count <= 5)   // Test the loop counter
    {
        Console::Write("\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 application. The application prompts you to enter the first date. After you have typed this date, the application prompts you to enter the second date. This process continues until you have typed five dates, at which point the application closes, as depicted in the following screen shot:

    httpatomoreillycomsourcemspimages1722380.jpg

Using for loops

The for loop is an alternative to the while loop. It provides more control over the way in which the loop executes.

The following example shows how to write a simple for loop in C++/CLI. This example has exactly the same effect as the while loop.

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

Console::WriteLine("The end");

The parentheses after the for keyword contain three expressions separated by semicolons. The first expression performs loop initialization, such as initializing the loop counter. This initialization expression is executed once only, at the start of the loop.

The second expression statement defines a test. If the test evaluates to true, the loop body is executed, but if it is false, the loop finishes and control passes to the statement that follows the closing parenthesis. 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 the loop counter.

The preceding example displays the output shown in the following screen shot.

httpatomoreillycomsourcemspimages1722382.jpg

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 main function to use a for loop rather than a while loop, as shown here:

    Console::WriteLine("Welcome to your calendar assistant");
    
    for (int count = 1; count <= 5; count++)
    {
        Console::Write("\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 displaying the date. This is because the for statement takes care of incrementing the loop counter.

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

Using do-while loops

The third loop construct you’ll look at here is the do-while loop (remember, there’s still the for-each loop, which you will meet later). The do-while loop is fundamentally different from the while and for loops because the test comes at the end of the loop body, which means that the loop body is always executed at least once.

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

Random ^r = gcnew Random();
int randomNumber;
int throws = 0;
do
{
    randomNumber = r->Next(1, 7);
    Console::WriteLine(randomNumber);
    throws++;
}
while (randomNumber != 6);

Console::Write("You took ");
Console::Write(throws);
Console::WriteLine(" 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 screen shot:

httpatomoreillycomsourcemspimages1722384.jpg

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, which forces the user to type a valid month:

    int GetMonth()
    {
        int month = 0;
        do
        {
            Console::Write("Month [1 to 12]? ");
            String ^input = Console::ReadLine();
            month = Convert::ToInt32(input);
        }
        while (month < 1 || month > 12);
        return month;
    }
  3. Modify the GetDay function as follows, which forces the user to type 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("Day [1 to ");
            Console::Write(maxDay);
            Console::Write("]? ");
            String ^input = Console::ReadLine();
            day = Convert::ToInt32(input);
        }
        while (day < 1 || day > maxDay);
        return day;
    }
  4. Build and run the application.

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

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

Performing unconditional jumps

C++/CLI provides two keywords—break and continue—with which you can 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.

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 main function as follows, which gives the user the option to break or continue if desired:

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

  4. After you type the first date, you are asked whether you want to break or continue. Press X (or any other key except B or C) and then press Enter to display the date as normal.

  5. Type the second date, and then press C followed by Enter, which causes the continue statement to be executed.

    The continue statement abandons the current iteration without displaying your date. Instead, you are asked to type the third date.

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