Decision and Loop Statements in Microsoft Visual C++

  • 8/15/2013
In this chapter from Microsoft Visual C++/CLI Step by Step, you will see how to use these statements to control the flow of execution through a C++/CLI application.

After completing this chapter, you will be able to:

  • Make decisions by using the if statement.

  • Make multiway decisions by using the switch statement.

  • Perform loops by using the while, for, and do-while statements.

  • Perform unconditional jumps in a loop by using the break and continue statements.

All high-level languages provide keywords with which you can make decisions and perform loops. C++ is no exception. C++ provides the if statement and the switch statement for making decisions, and it provides the while, for, and do-while statements for performing loops. In addition, C++ provides the break statement to exit a loop immediately and the continue statement to return to the start of the loop for the next iteration.

In this chapter, you will see how to use these statements to control the flow of execution through a C++/CLI application.

Making decisions by using the if statement

The most common way to make a decision in C++/CLI is to use the if statement. You can use the if statement to perform a one-way test, a two-way test, a multiway test, or a nested test. Let’s consider a simple one-way test first.

Performing one-way tests

The following example shows how to define a one-way test in C++/CLI:

if (number < 0)
    Console::WriteLine("The number is negative");
Console::WriteLine("The end");

The if keyword is followed by a conditional expression, which must be enclosed in parentheses. If the conditional expression evaluates to true, the next statement is executed, which in this example will display the message “The number is negative”. Notice that the message “The end” will always be displayed, regardless of the outcome of the test, because it is outside the body of the if statement.

In this exercise, you will create a new application to perform one-way tests. As this chapter progresses, you will extend the application to use more complex decision-making constructs and to perform loops. For now, the application asks the user to enter a date and then it performs simple validation and displays the date in a user-friendly format on the console.

  1. Start Visual Studio 2012 and create a new CLR Console Application project. Name the application CalendarAssistant.

  2. At the top of the source code file, immediately below the using namespace System; line, add the following function prototypes (you will implement all these functions during this chapter):

    int GetYear();
    int GetMonth();
    int GetDay(int year, int month);
    void DisplayDate(int year, int month, int day);
  3. At the end of the file, after the end of the main function, implement the GetYear function as follows:

    int GetYear()
    {
        Console::Write("Year? ");
        String ^input = Console::ReadLine();
        int year = Convert::ToInt32(input);
        return year;
    }
  4. Implement the GetMonth function as follows:

    int GetMonth()
    {
        Console::Write("Month? ");
        String ^input = Console::ReadLine();
        int month = Convert::ToInt32(input);
        return month;
    }

    This is a simplified implementation; later in this chapter, you will enhance the function to ensure that the user enters a valid month.

  5. Implement the GetDay function as follows:

    int GetDay(int year, int month)
    {
        Console::Write("Day? ");
        String ^input = Console::ReadLine();
        int day = Convert::ToInt32(input);
        return day;
    }

    Later, you will enhance this function to ensure that the user enters a valid day for the given year and month.

  6. Implement the DisplayDate function as shown in the following code to display the date as three numbers:

    void DisplayDate(int year, int month, int day)
    {
        Console::WriteLine("\nThis is the date you entered:");
        Console::Write(year);
        Console::Write("-");
        Console::Write(month);
        Console::Write("-");
        Console::Write(day);
        Console::WriteLine();
    }

    Later in this chapter you will enhance this function to display the date in a more user-friendly format.

  7. Add the following code inside the main method, immediately before the return 0; Line:

    Console::WriteLine("Welcome to your calendar assistant");
    Console::WriteLine("\nPlease enter a date");
    int year = GetYear();
    int month = GetMonth();
    int day = GetDay(year, month);
    // Simplified test for now - assume there are 31 days in
    // every month :-)
    if (month >= 1 && month <= 12 && day >= 1 && day <= 31
    )
    {
        DisplayDate(year, month, day);
    }
    Console::WriteLine("\nThe end\n");

    This code asks the user to enter a year, month, and day. If the date passes a simplified validation test, the date is displayed on the console. If the date is invalid, it is not displayed at all.

  8. Build the application and fix any compiler errors that you might have.

  9. Run the application. Type in valid numbers for the year, month, and day (for example, 2012, 7, and 22).

    The application displays the messages shown in the following screen shot:

    httpatomoreillycomsourcemspimages1722368.jpg

    Observe that the application displays the date because it is valid. The message “The End” also appears at the end of the program.

  10. Run the application again, but this time, type an invalid date (for example, 2012, 2, and 33). The application displays the messages shown in the following screen shot:

    httpatomoreillycomsourcemspimages1722370.jpg

    Notice that because the date you typed was invalid, the application doesn’t display it. Instead, it just displays “The End.” You can make the application more user-friendly by displaying an error message if the date is invalid. To do so, you need to use a two-way test.

Performing two-way tests

The following code shows how to define a two-way test for the Calendar Assistant application:

if (month >= 1 && month <= 12 && day >= 1 && day <= 31
)
{
    DisplayDate(year, month, day);
}
else
{
    Console::WriteLine("Invalid date");
}
Console::WriteLine("\nThe end\n");

The else body defines what action to perform if the test condition fails.

In this exercise, you will enhance your Calendar Assistant application to display an error message if an invalid date is entered.

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

  2. Modify the main function, replacing the simple if with an if-else statement to test for valid or invalid dates.

    if (month >= 1 && month <= 12 && day >= 1 && day <= 31
    )
    {
        DisplayDate(year, month, day);
    }
    else
    {
        Console::WriteLine("Invalid date");
    }
    Console::WriteLine("\nThe end\n");
  3. Build and run the application. Type an invalid date such as 2001, 0, and 31.

    The application now displays an error message, as demonstrated in the following screen shot:

    httpatomoreillycomsourcemspimages1722372.jpg

Performing multiway tests

You can arrange if-else statements in a cascading fashion to perform multiway decision making.

The following code shows how to use a multiway test to determine the maximum number of days (maxDay) in a month:

int maxDay;
if (month == 4 || month == 6 || month == 9 || month == 11)
{
    maxDay = 30;
}
else if (month == 2)
{
    maxDay = 28;
}
else
{
    maxDay = 31;
}

This code specifies that if the month is April, June, September, or November, set maxDay to 30. If the month is February, maxDay is set to 28. (We’ll ignore leap years for now!) If the month is anything else, set maxDay to 31.

In this exercise, you will enhance your Calendar Assistant application to display the maximum number of days in the user’s chosen month.

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

  2. Replace the GetDay function with the following code so that it uses an if-else-if statement to determine the maximum allowable number of days.

    int GetDay(int year, int month)
    {
        int maxDay;
        if (month == 4 || month == 6 || month == 9 || month == 11)
        {
            maxDay = 30;
        }
        else if (month == 2)
        {
            maxDay = 28;
        }
        else
        {
            maxDay = 31;
        }
        Console::Write("Day [1 to ");
        Console::Write(maxDay);
        Console::Write("]? ");
    
        String ^input = Console::ReadLine();
        int day = Convert::ToInt32(input);
        return day;
    }
  3. Build and run the application. Type the year 2012 and the month 1.

    The application prompts you to enter a day between 1 and 31, as illustrated in the following screen shot:

    httpatomoreillycomsourcemspimages1722374.jpg
  4. Type a valid day and close the console window when the date is displayed.

  5. Run the application again. Type the year 2012 and the month 2.

    The application prompts you to enter a day between 1 and 28, as shown here:

    httpatomoreillycomsourcemspimages1722376.jpg
  6. Type a valid day and close the console window when the date is displayed. (Don’t worry about the date validation in main: You will remove it later and replace it with more comprehensive validation in the GetMonth and GetDay functions.)

Performing nested tests

It is possible to nest tests within one another. This makes it possible for you to perform more complex logical operations. The following code shows how to use nested tests to accommodate leap years correctly in the Calendar Assistant application:

int maxDay;
if (month == 4 || month == 6 || month == 9 || month == 11)
{
    maxDay = 30;
}
else if (month == 2)
{
    bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    if (isLeapYear)
    {
        maxDay = 29;
    }
    else
    {
        maxDay = 28;
    }
}
else
{
    maxDay = 31;
}

If the month is February, you define a bool variable to determine if the year is a leap year. A year is a leap year if it is evenly divisible by 4 but not evenly divisible by 100 (except years that are evenly divisible by 400, which are leap years). The following table shows some examples of leap years and non–leap years.

Year

Leap year?

1996

Yes

1997

No

1900

No

2000

Yes

You then use a nested if statement to test the bool variable isLeapYear so that you can assign an appropriate value to maxDay.

In this exercise, you will enhance your Calendar Assistant application to deal correctly with leap years.

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

  2. Modify the GetDay function, replacing the if…else if…else statements to match the block of code just described to test for leap years.

  3. Build and run the application. Type the year 1996 and the month 2. The application prompts you to enter a day between 1 and 29. Type a valid day and then when the date is displayed, close the console window.

  4. Run the application again. Type the year 1997 and the month 2. Verify that the application prompts you to enter a day between 1 and 28.

  5. Run the application several more times using the test data from the previous table.