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