Visual C# 2005 Guide
Switch Statement

The switch statement examines the value of a variable and passes control to one of the case statements included within it.

Console.Write("Enter first number: ");
int num1 = System.Convert.ToInt32( Console.ReadLine());
Console.Write("Enter second number: ");
int num2 = System.Convert.ToInt32(Console.ReadLine());
Console.Clear();
Console.WriteLine("Numbers: {0} and {1}", num1, num2);
Console.Write("Enter 1 to add, 2 to subtract");
int switchCase = System.Convert.ToInt32(Console.ReadLine());
int answer = 0;
switch (switchCase)
{
   case 1:
      answer = num1 + num2;
      break;
   case 2:
      answer = num1 - num2;
      break;
   default:
      answer = num1 + num2;
      break;
}

Console.WriteLine("The answer is {0}", answer);
Console.ReadLine();

Copy and compile this program. Study the switch statement carefully. Each case is a block of code to be executed if the switchCase variable is that value. Each block must end with the break statement or you will get a compiler error. If you type a number other than 1 or 2, the default case takes over.

The values for each of the case statements can be strings or integer data types like char, byte, short but cannot be floating point values. The case statements must also refer to constants and not ranges of numbers. You cannot have two identical cases.

Having A Go

Feel free to use whichever of the selection techniques you find most useful for the following programs. A combination of the types of statement covered in this section will probably be required.

  1. Ask the user to input the number of a month. Display the name of the corresponding month.
  2. A year is a leap year if it is exactly divisible by 4 unless it is a century, in which case it must be divisible by 400 to be a leap year. Ask the user to enter a year and tell them whether or not it was a leap year. There is a built-in function, I know, but go with this.
  3. Ask the user for a month number and tell them the number of days in the month.
  4. Write a program that allows the user to enter a Module 1 examination score as an integer in the range 0 - 65. Convert the score into a grade using the boundaries specified below,

    A - 47, B - 42, C - 37, D - 33, E - 29
     
  5. Write a program which allows the user to input a number in the range 1 - 10. If the user has entered a number in the range, output the number in words to the screen. If they enter a number out of range, display an error message telling them off.