Switch is a selection statement to execute a single statement from a list of multiple statement based on pattern match with the expression.
The switch expression is used with integer type such as int, char, byte, or short, an enumeration type, or of string type. The expression is checked for various cases and the one match is executed.
Switch can be used in place of if-else statement to provide better readability of code.
Syntax
switch(expresion)
{ case value1:
//statement to execute
break;
case value2:
//statement to execute
break;
…….
…….
default:
//statement to execute if no case matches
break;
}
Why do we use Switch Statements instead of if-else statements?
We generally use a switch statement instead of if-else statements because if-else statement
works only for a small number of logical evaluations of a value. If we use if-else statement for a larger number of possible conditions then, it will take more time to write and also become difficult to read.
// C# program to illustrate
// switch case statement
using System;
public class GFG {
// Main Method
public static void Main(String[] args)
{
int nitem = 5;
switch (nitem) {
case 1:
Console.WriteLine("case 1");
break;
case 5:
Console.WriteLine("case 5");
break;
case 9:
Console.WriteLine("case 9");
break;
default:
Console.WriteLine("No match found");
break;
}
}
}
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Switch is a selection statement to execute a single statement from a list of multiple statement based on pattern match with the expression.
The switch expression is used with integer type such as int, char, byte, or short, an enumeration type, or of string type. The expression is checked for various cases and the one match is executed.
Switch can be used in place of if-else statement to provide better readability of code.
Syntax
Why do we use Switch Statements instead of if-else statements?
We generally use a switch statement instead of if-else statements because if-else statement works only for a small number of logical evaluations of a value. If we use if-else statement for a larger number of possible conditions then, it will take more time to write and also become difficult to read.