Tuesday, January 3, 2012

2.1.9. switch

If there are several possible values for a variable, there is a better option than using many consecutive "if" command: the "switch" statement, whose syntax is

  switch (expression)
  {
     case value1: statement1;
            break;
     case value2: statement2;
            statement2b;
            break;
      ...
     case valueN: statementN;
            break;
    default:
            otherStatement;
            break;
  }

That is: after "switch" we write in parentheses the expression to be analyze. Then we use several "case" statements, one for each possible value. The steps to be taken for each value must end with "break". If something must be done in case of not meeting any previous condition, we can a add a "default" clause.

Also, if two cases have to achieve the same result, we must add "goto case" one of them to indicate it. Let's see an example, to say if the symbol entered by the user is a digit, a space or other symbol. We will use a data type called "char" (character), which we will see in more detail in the next topic. At this moment, it is enough for us to know that we can read a letter from keyboard using Convert.ToChar(Console.ReadLine), and we can assign it a value (or compare it) using single quotes:

/*---------------------------*/
/*  C# Example #14:          */
/*  example14.cs             */
/*                           */
/*  "switch" statement (1)   */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example14
{
  public static void Main()
  {
    char letter;

    Console.WriteLine("Enter a letter");
    letter = Convert.ToChar( Console.ReadLine() );
   
    switch (letter)
    {
      case ' ': Console.WriteLine("Blank space.");
                break;
      case '1': goto case '0';
      case '2': goto case '0';
      case '3': goto case '0';
      case '4': goto case '0';
      case '5': goto case '0';
      case '6': goto case '0';
      case '7': goto case '0';
      case '8': goto case '0';
      case '9': goto case '0';
      case '0': Console.WriteLine("Digit.");
                break;
      default:  Console.WriteLine("Neither space nor digit.");
                break;
    }
  }
}


An important detail for C programmers: in C we can let a case be handled by the following case, and this is achieved by not using "break". But in C# we must always use "break" or "goto" in the end each each case, with only the exception of a case which does absolutely nothing but passing control to the next case, and then it can be left completely empty:

/*---------------------------*/
/*  C# Example #14b:         */
/*  example14b.cs            */
/*                           */
/*  "switch" statement  (1b) */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example14b
{
  public static void Main()
  {
    char letter;

    Console.WriteLine("Enter a letter");
    letter = Convert.ToChar( Console.ReadLine() );

    switch (letter)
    {
      case ' ': Console.WriteLine("Blank space.");
                break;
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
      case '0': Console.WriteLine("Digit.");
                break;
      default:  Console.WriteLine("Neither space nor digit.");
                break;
    }
  }
}

Also, in C you could only use "switch" to check values "simple" values (numbers and characters), but C# also can check text strings.

A text string, as discussed in more detail in the next topic, is declared with the word "string", can be read from keyboard using ReadLine (no need to convert) and can be assigned a value (or compared) using double quotes, like this:

/*---------------------------*/
/*  C# Example #15:          */
/*  example15.cs             */
/*                           */
/*  "switch" statement  (2)  */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example15
{
  public static void Main()
  {
    string name;

    Console.WriteLine("Enter your name");
    name = Console.ReadLine();
   
    switch (name)
    {
      case "John": Console.WriteLine("Welcome, John.");
                break;
      case "Peter": Console.WriteLine("How are you, Peter");
                break;         
      default:  Console.WriteLine("Proceed with caution, unknown.");
                break;
    }
  }
}


Suggested exercises:
Ø     Create a program to read a letter entered by the user and say if it is a vowel, a numerical figure or a consonant (hint: you must use a data type "char").
Ø     Create a program to read a letter entered by the user and say if it is a punctuation mark, a digit or some other character.
Ø     Repeat the previous two programs, using "if" instead of "switch".

No comments:

Post a Comment