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
1. string input;
2.  
3. // Prompt the user to select a 1- or 2- player game
4. Console.Write($"""
5.         1 - Play against the computer
6.         2 - Play against another player.
7.         Choose:
8.         """
9. );
10. input = Console.ReadLine();
11.  
12. if (input == "1")
13.     // The user selected to play the computer
14.     Console.WriteLine(
15.         "Play against computer selected.");
16. else
17.     // Default to 2 players (even if user didn't enter 2)
18.     Console.WriteLine(
19.         "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
1. int input;    // Declare a variable to store the input
2.  
3. Console.Write(
4.     "What is the maximum number " +
5.     "of turns in tic-tac-toe?" +
6.     " (Enter 0 to exit.): ");
7.  
8. // int.Parse() converts the ReadLine()
9. // return to an int data type
10. input = int.Parse(Console.ReadLine());
11.  
12. // Condition 1.
13. if (input <= 0) // line 16
14.     // Input is less than or equal to 0
15.     Console.WriteLine("Exiting...");
16. else
17.     // Condition 2.
18.     if (input < 9) // line 20
19.         // Input is less than 9
20.         Console.WriteLine(
21.             $"Tic-tac-toe has more than {input}" +
22.             " maximum turns.");
23.     else
24.         // Condition 3.
25.         if (input > 9) // line 26
26.             // Input is greater than 9
27.             Console.WriteLine(
28.                 $"Tic-tac-toe has fewer than {input}" +
29.                 " maximum turns.");
30.         // Condition 4.
31.         else
32.             // Input equals 9
33.             Console.WriteLine(  // line 33
34.                 "Correct, tic-tac-toe " +
35.                 "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
1. if (input < 0)
2.     Console.WriteLine("Exiting...");
3. else if(input < 9)
4.     Console.WriteLine(
5.         $"Tic-tac-toe has more than {input}" +
6.         " maximum turns.");
7. else if (input > 9)
8.     Console.WriteLine(
9.         $"Tic-tac-toe has less than {input}" +
10.         " maximum turns.");
11. else
12.     Console.WriteLine(
13.         "Correct, tic-tac-toe has a maximum" +
14.         " 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 }}
;