The switch-case statement
Explains the use of a switch case statement for decision-based functions in programming
The switch-case statement is also used for making decision. However, unlike the if-else statement, we can not test conditions like `greater than' or `less than'. In a switch-case, we can test the value of a variable and decide what to do if a particular value is stored in the variable. The syntax for the switch-case is:
switch(variable to test)
{
case value1:
statements if value1 stored in the variable;
break;
case value2:
statements if value12 stored in the variable;
break;
.
.
.
default:
statements if none of the values match;
break;
}
To understand this, let us create a program. The user will enter a weekday number (1 to 7) and the program will display the name of the corresponding day:
static void Main(string[] args) { int day;
Console.WriteLine("Enter a weekday number (1-7)"); day = int.Parse(Console.ReadLine()); switch (day)
{ case 1: Console.WriteLine("Sunday");
break;
case 2: Console.WriteLine("Monday");
break;
case 3: Console.WriteLine("Tuesday");
break;
case 4: Console.WriteLine("Wednesday");
break;
case 5: Console.WriteLine("Thursday");
break;
case 6: Console.WriteLine("Friday");
break;
case 7: Console.WriteLine("Sunday");
break;
default: Console.WriteLine("Invalid Input");
break;
}
}
In the above code, the value stored in the variable `day' is tested. If the value is 1, the first case will match and the statement in it will execute. Then the keyword `break' will terminate the switch-case. If the value is 2, the second case will match and so on. If the user enters a value that does not match any case, the statement in the default section will execute.
As we can see, to use the switch-case, there has to be some some idea of the values that will be tested. Further, we cannot use comparisons like x>y in the switch-case statement. That is why the if-else statement is the preferred one for decision-making.