Introducing Flow Control

Toward the end of this chapter is a code listing (Listing 3.42) 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.

An embedded-statement in Table 3.1 corresponds to any statement, including a code block (but not a declaration statement or a label).

Table 3.1. Control Flow Statements


General Syntax Structure


if statement

 if(booleanexpression)   embeddedstatement 

 if (input == "quit") {   Console.WriteLine("Game end");   return; } 


 if(booleanexpression)   embeddedstatement else    embeddedstatement 

 if (input == "quit") {   Console.WriteLine("Game end");   return; } else   GetNextMove(); 

while statement

 while(booleanexpression)  embeddedstatement 

 while(count < total) {   Console.WriteLine("count = {0}", count);   count++; } 

do while statement

 do   embeddedstatement while(booleanexpression); 

 do {  Console.WriteLine("Enter name:");  input = Console.ReadLine(); } while(input != "exit"); 

for statement

 for(forinitializer;     booleanexpression;     foriterator)   embeddedstatement 

 for (int count = 1; count <= 10; count++) {  Console.WriteLine("count = {0}", count); } 

foreach statement

 foreach(type identifier in       expression)   embeddedstatement 

 foreach (char letter in email) {  if(!insideDomain)  {   if (letter == '@')   {     insideDomain = true;   }    continue;  }  Console.Write(letter); } 

continue statement



switch statement

 switch(governingtype expression) {  ...  case constexpression:    statementlist    jumpstatement  default:    statementlist    jumpstatement } 

 switch(input) {  case "exit":  case "quit":      Console.WriteLine("Exiting app....");      break;  case "restart":      Reset();      goto case "start";  case "start":      GetMove();      break;  default:      Console.WriteLine(input);      break; } 

break statement



goto statement

goto identifier;


goto case const-expression


goto default;


Each C# control flow statement in Table 3.1 appears in the tic-tac-toe program found in Appendix B. The program displays the tic-tactoe 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 forward to the conclusion.

if Statement

The if statement is one of the most common statements in C#. It evaluates a Boolean expression(an expression that returns a Boolean), and if the result is true, the following statement (or block) is executed. The general form is as follows:

if(booleanexpression)  truestatement [else  falsestatement]

There is also an optional else clause for when the Boolean expression is false. Listing 3.20 shows an example.

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 a 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 tictactoe.

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 tictactoe?" + 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                 "Tictactoe 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                           "Tictactoe has fewer than {0}" + 30                           " maximum turns.", input); 31                else 32                       // Input equals 9. 33                       System.Console.WriteLine( 34                          "Correct, " + 35                          "tictactoe has a max. of 9 turns."); 36      } 37   }

Output 3.13 shows the results of Listing 3.21

Output 3.13.

[View full width]

What's the maximum number of turns in tictactoe? (Enter 0 to exit.): 9 Correct,  tictactoe has a max. of 9 turns.

Assume the user enters a 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.

Listing 3.22. if/else Formatted Sequentially

if (input < 0)      System.Console.WriteLine("Exiting..."); else if (input < 9)      System.Console.WriteLine(           "Tictactoe has more than {0}" +           " maximum turns.", input); else if(input>9)      System.Console.WriteLine(           "Tictactoe has less than {0}" +           " maximum turns.", input);    else      System.Console.WriteLine(          "Correct, tictactoe 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.

Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185 © 2008-2017.
If you may any questions please contact us: