Switch and Looping
Switch and Looping
Switch and Looping
AND
INTRODUCTION TO
LOOPING
Review
• You can test a series of condition with the…
• if-else if statement
• Nesting is…
• enclosing one structure inside of another.
• Binary logical operators combine…
• two boolean expressions into one.
• Binary logical operators:
• &&
• ||
switch (SwitchExpression) {
case CaseExpression1:
//One or more statements
break;
case CaseExpression2:
//One or more statements
break;
default:
//One or more statements
}
• switch – keyword that begins a switch statement
• SwitchExpression – a variable or expression that has to be either char, byte, short, or int.
• case – keyword that begins a case statement (there can be any number of case statements)
• CaseExpression1 – a literal or final variable that is of the same type as SwitchExpression .
The switch Statement
• General form of a switch statement:
switch (SwitchExpression) {
case CaseExpression1:
//One or more statements
break;
case CaseExpression2:
//One or more statements
break;
default:
//One or more statements
}
• Inside a case statement, one or more valid programming statements may appear.
• After the statement(s) inside of a case statement’s block, often the keyword break appears.
• After all of the case statements, there is the default case, which begins with the keyword default.
The switch Statement
• General form of a switch statement:
switch (SwitchExpression) {
case CaseExpression1:
//One or more statements
break;
case CaseExpression2:
//One or more statements
break;
default:
//One or more statements
}
• What this does is compare the value of SwitchExpression to each CaseExpressions.
• If they are equal, the statements after the matching case statement are executed.
• Once the break keyword is reached, the statements after the switch statement’s block are executed.
• break is a keyword that breaks the control of the program out of the current block.
• If none of the CaseExpressions are equal to SwitchExpression, then the statements below the default case
are executed.
The switch Statement
if (x == 1)
y = 4;
if else (x == 2)
y = 9;
else
y = 22;
Is the same as…
switch (x) {
case 1:
y = 4;
break;
case 2:
y = 9;
break;
default:
y = 22;
}
switch Statement Example
• New Topics:
• The switch Statement
The switch Statement Notes
• The CaseExpression of each case statement must be unique.
while (BooleanExpression)
Statement or Block
• First, the BooleanExpression is tested
• If it is true, the Statement or Block is executed
• After the Statement or Block is done executing, the BooleanExpression
is tested again
• If it is still true, the Statement or Block is executed again
• This continues until the test of the BooleanExpression results in false.
Boolean True
Statement or Block
Expression
False
while Loop Example
• New Topics:
• while Loop
number True
Print “Hello!” number++
<= 5
False
Statement or Block
True
Boolean
Expression
False
do-while Loop Example
• New Topic:
• do-while Loop