Home > Sample chapters

Decision and Loop Statements in Microsoft Visual C++

Quick reference

To

Do this

Perform a one-way test.

Use the if keyword followed by a test enclosed in parentheses. You must enclose the if body in braces if it contains more than one statement. For example:

if (n < 0)
{
    Console::Write("The number ");
    Console::Write(n);
    Console::WriteLine(" is negative");
}

Perform a two-way test.

Use an if-else construct. For example:

if (n < 0)
{
    Console::Write("Negative");
}
else
{
    Console::Write("Not negative");
}

Perform a multiway test.

Use an if-else-if construct. For example:

if (n < 0)
{
    Console::Write("Negative");
}
else if (n == 0)
{
    Console::Write("Zero");
}
else
{
    Console::Write("Positive");
}

Test a single expression against a finite set of constant values.

Use the switch keyword followed by an integral expression enclosed in parentheses. Define case branches for each value you want to test against, and define a default branch for all other values. Use the break statement to close a branch. For example:

int dayNumber; // 0=Sun, 1=Mon, etc.
...
switch (dayNumber)
{
case 0:
case 6:
    Console::Write("Weekend");
    break;
default:
    Console::Write("Weekday");
    break;
}

Perform iteration by using the while loop.

Use the while keyword followed by a test enclosed in parentheses. For example:

int n = 10;
while (n >= 0)
{
    Console::WriteLine(n);
    n--;
}

Perform iteration by using the for loop.

Use the for keyword followed by a pair of parentheses. Within the parentheses, define an initialization expression, followed by a test expression, followed by an update expression. Use semicolons to separate these expressions. For example:

for (int n = 10; n >= 0; n--)
{
    Console::WriteLine(n);
}

Perform iteration by using the do-while loop.

Use the do keyword, followed by the loop body, followed by the while keyword and the test condition. Terminate the loop with a semicolon. For example:

int n;
do
{
    String^ input = Console::ReadLine();
    n = Convert::ToInt32(input);
} while (n > 100);

Terminate a loop prematurely.

Use the break statement inside any loop. For example:

for (int n = 0; n < 1000; n++)
{
    int square = n * n;
    if (square > 3500)
    {
        break;
    }
    Console::WriteLine(square);
}

Abandon a loop iteration and continue with the next iteration.

Use the continue statement inside any loop. For example:

for (int n = 0; n < 1000; n++)
{
    int square = n * n;
    if (square % 2 == 0)
    {
        continue;
    }
    Console::WriteLine(square);
}