Topic 4 - Control - Structures-Switch
Topic 4 - Control - Structures-Switch
CONTROL
STRUCTURE
S
Switch ..case
1
WHAT IS
Switch ..case?
Similar to an if statement,
a switch statement allows a
variable/expression to be
examined against a list of
options.
switch (variable/expression)
{
case value1: statements1
break;
case value2: statements2
break;
...
case valuen: statementsn
break;
default: statements
break;
}
NESTED If & Switch
STATEMENT
int month = 2;
if (month == 1)
System.out.println("Month is Jan");
else if (month == 2)
System.out.println("Month is Feb");
else if (month == 3)
System.out.println("Month is March");
else
System.out.println("Not the first quarter of the year");
int month = 2;
switch (month){
case 1: System.out.println("Month is Jan");break;
case 2: System.out.println("Month is Feb"); break;
case 3: System.out.println("Month is March"); break;
default: System.out.println("Not the first quarter of the year");
}
THE Break STATEMENT
Output: Output:
m=2 ch=b
ch=c
default
Switch EXAMPLES
break;
}
Switch AND NESTED If EXAMPLE
int number=1, x = 2;
else
number+=5;
switch Example
int i = 1; int i = 1;
int j = 0; int j = 0;
switch (i+1) {
switch (i+1) {
case 0: j = 0;break;
case 0: j = 0; case 1: j = 1;break;
case 1: j = 1; case 2: j = 3;break;
case 2: j = 3; default: j = -2;break;
default: j = -2; }
}
j=-2 j=3
Exercise
Rewrite the following if statement using a switch:
int selection;
if (selection == 1)
System.out.println("You selected JAVA");
else if (selection == 2)
System.out.println("You selected VISUAL BASIC");
else if(selection == 3)
System.out.println("You selected PHP");
else
System.out.println("Invalid selection");
Exercise
Rewrite the following switch using if else statement :
Switch selection
control structure.
Nested If & Switch
statement.
Break statement.
14