Switch_Quiz.md - brainchildservices/curriculum GitHub Wiki
-
Define C# Switch Statements?
In C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type. The expression is checked for different cases and the one match is executed.
-
Why do we use Switch Statements instead of if-else statements?
- We use a switch statement instead of if-else statements because if-else statement only works for a small number of logical evaluations of a value. If you use if-else statement for a larger number of possible conditions then, it takes more time to write and also become difficult to read.
- break statement is used to exit from the switch statement.
- goto statement can be used to go to a different case of the switch statement.
-
What will be the output of the following C# code?
static void Main(string[] args)
{
int movie = 1;
switch (movie << 2 + movie)
{
default:
Console.WriteLine("3 Idiots");
break;
case 4:
Console.WriteLine("Ghazini");
break;
case 5: Console.WriteLine("Krishh");
break;
case 8: Console.WriteLine("Race");
break;
}
Console.ReadLine();
}- 3 Idiots
- Ghazini
- Race
- Krishh
Ans :- Race
-
What will be the output of the following C# code?
static void Main(string[] args)
{
int i = 2, j = 4;
switch (i + j * 2)
{
case 1 :
case 2 :
Console.WriteLine("1 and 2");
break;
case 3 to 10:
Console.WriteLine("3 to 10");
break;
}
Console.ReadLine();
}- 3 to 10 will be printed
- 1 and 2 will be printed
- The code reports an error as missing ; before :
- The code gives output as 3 to 10
Ans :- The code reports an error as missing ; before :