2. Introduction
There are three types of program control statements:-
1. Selection Statements
if
switch
2. Iteration Statements
for
while
do-while
foreach
3.Jump Statements
break
goto
continue
return
throw
3. Switch Statement
The switch statement tests the value of a given variable (or expression) against a list of case values
and when match is found, a block of statements associated with that case is executed.
The general form of switch statement is :-
switch(expression)
{
case value-1:
block-1
break;
case value-2:
block-1
break
case value-n:
block-1
break
default:
default –block
break;
}
4. Switch Statement(Contd.)
using System;
class bulb
{
public static void Main()
{
Console.WriteLine("Select your choice");
Console.WriteLine("London");
Console.WriteLine("Bombay");
Console.WriteLine("Paris");
Console.WriteLine("Type your choice");
String name=Console.ReadLine();
switch(name)
{
case " Bombay":
Console.WriteLine("Bombay:Guide5");
break;
case " London":
Console.WriteLine("London:Guide10");
break;
case " Paris":
Console.WriteLine("Paris:Guide15");
break;
default:
Console.WriteLine("Invalid Choice");
break;
5. Fallthrough in Switch Statement
In the absence of break statement in a case block, if the control moves
to the next case block without any problem, it is known as
‘FALLTHROUGH’.
‘FALLTHROUGH’ is permitted in C,C++ and JAVA. But C# doesn't
permit automatic fallthrough, if the case block contains executable code.
switch(m)
{
case 1:
x=y;
case 2:
x=y+m;
default :
x=y-m;
}
is an error in C#.
6. Fallthrough in Switch
Statement(Contd..)
If we want two consecutive case blocks to be executed continuously,
we have to force the process by using the goto statement.
switch(m)
{
case 1:
x=y;
goto case 2;
case 2:
x=y+m;
goto default;
default:
x=y-m;
break;
}
7. Fallthrough in Switch
Statement(Contd..)
The goto mechanisms enable us to jump backward and forward between
cases and therefore arrange labels arbitrarily:
Switch(m)
{
default:
x=y-m;
break;
case 2:
x=y+m;
goto default;
case 1:
x=y;
goto case 2;
}
8. Foreach statement
The foreach statement is similar to the for statement but implemented
differently.
foreach(type variable in expression)
{
Body of the Loop
}
public static void Main()
{
foreach(string s in args)
{
Console.WriteLine(s);
}
}
We cannot change the iteration variable during execution.