Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Introducing Flow Control

Later in this chapter is a code listing (Listing 3.43) 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 on, you will learn how to execute statement groups repeatedly through loop constructs.

A summary of the control flow statements appears in Table 3.1. Note that the General Syntax Structure column indicates common statement use, not the complete lexical structure.

Table 3.1. Control Flow Statements

Statement

General Syntax Structure

Example

if statement

if(boolean-expression)
  embedded-statement
if (input == "quit")
{
  System.Console.WriteLine(
    "Game end");
  return;
}

if(boolean-expression)
  embedded-statement
else
  embedded-statement
if (input == "quit")
{
  System.Console.WriteLine(
    "Game end");
  return;
}
else
  GetNextMove();

while statement

while(boolean-expression)
  embedded-statement
while(count < total)
{
  System.Console.WriteLine(
    "count = {0}", count);
  count++;
}

do while statement

do
  embedded-statement while(boolean-expression);
do
{
  System.Console.WriteLine(
    "Enter name:");
  input =
     System.Console.ReadLine();
}
while(input != "exit")
;

for statement

for(for-initializer;
     boolean-expression;
     for-iterator)
  embedded-statement
for (int count = 1;
   count <= 10;
   count++)
{
  System.Console.WriteLine(
    "count = {0}", count);
}

foreach statement

foreach(type identifier in
     expression)
  embedded-statement
foreach (char letter in email)
{  if(!insideDomain)
  {
    if (letter == '@')
    {
      insideDomain = true;
    }
    continue;
  }
  System.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":
    System.Console.WriteLine(
      "Exiting app....");
    break;
  case "restart":
    Reset();
    goto case "start";
  case "start":
     GetMove();
     break;
  default:
    System.Console.WriteLine(
      input);
    break;
}

break statement

break;

goto statement

goto identifier;
goto case const-expression;
goto default;

An embedded-statement in Table 3.1 may be any statement other than a labeled statement or a declaration, but it is typically a block statement.

Each C# control flow statement in Table 3.1 appears in the tic-tac-toe3 program and is available in Appendix B and for download with the rest of the source code listings from the book. The program displays the tic-tac-toe board, prompts each player, and updates with each move.

The remainder 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 the table familiar because of C#’s similarities to other languages can jump ahead to the section titled C# Preprocessor Directives or skip to the Summary section at the end of the chapter.

The remainder 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 the table familiar because of C#’s similarities to other languages can jump ahead to the section titled C# Preprocessor Directives or skip to the Summary section 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 is executed. 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

Listing 3.20. if/else Statement Example

class TicTacToe      // Declares the TicTacToe class.
{
  static void Main() // Declares the entry point of the program.
  {
      string input;

      // Prompt the user to select a 1- or 2-player game.
      System.Console.Write (
          "1 – Play against the computer\n" +
          "2 – Play against another player.\n" +
          "Choose:"
      );
      input = System.Console.ReadLine();

      if(input=="1")                                                                       
          // The user selected to play the computer.                                       
          System.Console.WriteLine(                                                        
              "Play against computer selected.");                                          
      else                                                                                 
          // Default to 2 players (even if user didn't enter 2).                           
          System.Console.WriteLine(                                                        
              "Play against another player.");                                             
  }
}

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

Nested if

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

Listing 3.21. Nested if Statements

1.  class TicTacToeTrivia
2.  {
3.    static void Main()
4.    {
5.        int input;    // Declare a variable to store the input.
6.  
7.        System.Console.Write(
8.            "What is the maximum number " +
9.            "of turns in tic-tac-toe?" +
10.           "(Enter 0 to exit.): ");
11.
12.       // int.Parse() converts the ReadLine()
13.       // return to an int data type.
14.       input = int.Parse(System.Console.ReadLine());
15.
16.       if (input <= 0)
17.               // Input is less than or equal to 0.
18.           System.Console.WriteLine("Exiting...");
19.       else
20.           if (input < 9)
21.               // Input is less than 9.
22.               System.Console.WriteLine(
23.                   "Tic-tac-toe has more than {0}" +
24.                   " maximum turns.", input);
25.           else
26.               if(input>9)
27.                   // Input is greater than 9.
28.                   System.Console.WriteLine(
29.                       "Tic-tac-toe has fewer than {0}" +
30.                       " maximum turns.", input);
31.               else
32.                   // Input equals 9.
33.                   System.Console.WriteLine(
34.                       "Correct, tic-tac-toe " +
35.                       "has a max. of 9 turns.");
36.   }
37. }

Output 3.13 shows the results of Listing 3.21.

Output 3.13.

What is the maximum number of turns in tic-tac-toe? (Enter 0 to exit.): 9
Correct, tic-tac-toe has a max. of 9 turns.

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

  1. Line 16: Check if input is less than 0. Since it is not, jump to line 20.
  2. Line 20: Check if input is less than 9. Since it is not, jump to line 26.
  3. Line 26: Check if input is greater than 9. Since it is not, jump to line 33.
  4. Line 33: Display that the answer was correct.

Listing 3.21 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. Without indenting and without newlines, the execution would be the same. The code that appears in the nested if statement in Listing 3.22 is equivalent to Listing 3.21.

Listing 3.22. if/else Formatted Sequentially

if (input < 0)
  System.Console.WriteLine("Exiting...");
else if (input < 9)
  System.Console.WriteLine(
      "Tic-tac-toe has more than {0}" +
      " maximum turns.", input);
else if(input < 9)
  System.Console.WriteLine(
      "Tic-tac-toe has less than {0}" +
      " maximum turns.", input);
else
  System.Console.WriteLine(
      "Correct, tic-tac-toe has a maximum " +
      " of 9 turns.");

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

Each if statement listing above omits the use of 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.

  • + Share This
  • 🔖 Save To Your Account