Introducing Flow Control

Later in this chapter is a code listing (Listing 4.46) that shows a simple way to view a number in its binary form. Even such a simple program, however, cannot be written without using control flow statements. Such statements control the execution path of the program. This section discusses how to change the order of statement execution based on conditional checks. Later, you will learn how to execute statement groups repeatedly through loop constructs.

A summary of the control flow statements appears in Table 4.1. Note that the General Syntax Structure column indicates common statement use, not the complete lexical structure. An embedded-statement in Table 4.1 may be any statement other than a labeled statement or a declaration but is frequently multiple statements combined into a code block as defined later in this section.

Table 4.1: Control Flow Statements

Statement

General Syntax Structure

Example

if statement

if(boolean-expression)

   embedded-statement

if (input == "quit")

{

   Console.WriteLine(

     "Game end");

   return;

}

if(boolean-expression)

   embedded-statement

else

   embedded-statement

if (input == "quit")

{

   Console.WriteLine(

     "Game end");

   return;

}

else

   GetNextMove();

while statement

while(boolean-expression)

   embedded-statement

while(count < total)

{

   Console.WriteLine(

     $"count = {count}");

   count++;

}

do while statement

do

   embedded-statement while(boolean-expression);

do

{

   Console.WriteLine(

     "Enter name:");

   input =

     Console.ReadLine();

}

while(input != "exit");

for statement

for(for-initializer;

     boolean-expression;

     for-iterator)

   embedded-statement

for (int count = 1;

   count <= 10;

   count++)

{

   Console.WriteLine(

     $"count = {count}");

}

foreach statement

foreach(type identifier in

      expression)

   embedded-statement

foreach (char letter in email)

{

   if(!insideDomain)

   {

     if (letter == '@')

     {

       insideDomain = true;

     }

     continue;

   }

   Console.Write(

     letter);

}

continue statement

continue;

switch statement

switch(governing-type-expression)

{

   ...

   case const-expression:

     statement-list

     jump-statement

   default:

     statement-list

     jump-statement

}

switch(input)

{

   case "exit":

   case "quit":

     Console.WriteLine(

       "Exiting app....");

     break;

   case "restart":

     Reset();

     goto case "start";

   case "start":

      GetNextMove();

      break;

   default:

     Console.WriteLine(

       input);

     break;

}

break statement

break;

goto statement

goto identifier;

goto case const-expression;

goto default;

Each C# control flow statement in Table 4.1 appears in the tic-tac-toe2 program and is available in Chapter 4’s source code in the file TicTacToe.cs. The program displays the tic-tac-toe board, prompts each player, and updates with each move.

The rest of this chapter looks at each statement in more detail. After covering the if statement, it introduces code blocks, scope, Boolean expressions, and bitwise operators before continuing with the remaining control flow statements. Readers who find Table 4.1 familiar because of C#’s similarities to other languages can jump ahead to the section titled “C# Preprocessor Directives” or skip to the Summary at the end of the chapter.

if Statement

The if statement is one of the most common statements in C#. It evaluates a Boolean expression (an expression that results in either true or false) called the condition. If the condition is true, the consequence statement executes. An if statement may optionally have an else clause that contains an alternative statement to be executed if the condition is false. The general form is as follows:

if (condition)

   consequence-statement

else

   alternative-statement

In Listing 4.21, if the user enters 1, the program displays Play against computer selected. Otherwise, it displays Play against another player.

Listing 4.21: if/else Statement Example
string input;
 
// Prompt the user to select a 1- or 2- player game
Console.Write($"""
        1 - Play against the computer
        2 - Play against another player.
        Choose:
        """
);
input = Console.ReadLine();
 
if (input == "1")
    // The user selected to play the computer
    Console.WriteLine(
        "Play against computer selected.");
else
    // Default to 2 players (even if user didn't enter 2)
    Console.WriteLine(
        "Play against another player.");
Nested if

Sometimes code requires multiple if statements. The code in Listing 4.22 first determines whether the user has chosen to exit by entering a number less than or equal to 0; if the user has not chosen to exit, it checks whether the user knows the maximum number of turns in tic-tac-toe (see accompanying Output 4.13).

Listing 4.22: Nested if Statements
int input;    // Declare a variable to store the input
 
Console.Write(
    "What is the maximum number " +
    "of turns in tic-tac-toe?" +
    " (Enter 0 to exit.): ");
 
// int.Parse() converts the ReadLine()
// return to an int data type
input = int.Parse(Console.ReadLine());
 
// Condition 1.
if (input <= 0) // line 16
    // Input is less than or equal to 0
    Console.WriteLine("Exiting...");
else
    // Condition 2.
    if (input < 9) // line 20
        // Input is less than 9
        Console.WriteLine(
            $"Tic-tac-toe has more than {input}" +
            " maximum turns.");
    else
        // Condition 3.
        if (input > 9) // line 26
            // Input is greater than 9
            Console.WriteLine(
                $"Tic-tac-toe has fewer than {input}" +
                " maximum turns.");
        // Condition 4.
        else
            // Input equals 9
            Console.WriteLine(  // line 33
                "Correct, tic-tac-toe " +
                "has a maximum of 9 turns.");
Output 4.13
What is the maximum number of turns in tic-tac-toe? (Enter 0 to exit.): 9
Correct, tic-tac-toe has a maximum of 9 turns.

Assume the user enters 9 when prompted at line 14. Here is the execution path:

1.
Condition 1: Check if input is less than 0. Since it is not, jump to Condition 2.
2.
Condition 2: Check if input is less than 9. Since it is not, jump to Condition 3.
3.
Condition 3: Check if input is greater than 9. Since it is not, jump to Condition 4.
4.
Condition 4: Display that the answer was correct.

Listing 4.22 contains nested if statements. To clarify the nesting, the lines are indented. However, as you learned in Chapter 1, whitespace does not affect the execution path. If this code was written without the indenting and without the newlines, the execution would be the same. The code that appears in the nested if statement in Listing 4.23 is equivalent to Listing 4.22.

Listing 4.23: if/else Formatted Sequentially
if (input < 0)
    Console.WriteLine("Exiting...");
else if(input < 9)
    Console.WriteLine(
        $"Tic-tac-toe has more than {input}" +
        " maximum turns.");
else if (input > 9)
    Console.WriteLine(
        $"Tic-tac-toe has less than {input}" +
        " maximum turns.");
else
    Console.WriteLine(
        "Correct, tic-tac-toe has a maximum" +
        " of 9 turns.");

Although the latter format is more common, in each situation you should use the format that results in the clearest code.

Both of the if statement listings omit the braces. However, as discussed next, this is not in accordance with the guidelines, which advocate the use of code blocks except, perhaps, in the simplest of single-line scenarios.

________________________________________

2. Known as noughts and crosses to readers outside the United States.
{{ snackbarMessage }}