Control Structures: Muhammad Niswar
Control Structures: Muhammad Niswar
Muhammad Niswar
Outline
Decision:
IF-ELSE
Switch Statement
Repetition (loop):
while
do-while
for
Decision
Execute different sections of code according to
certain conditions
IF Statement
Perform action when condition is TRUE
Single input and output control structure
IF Statement
if ( boolean_expression)
statement;
true false
if ( boolean_expression) { boolean_expr
statement1;
statement2;
statement3; statement
……………
}
IF-ELSE Statement
Perform action when condition is TRUE
Perform different action when condition is FALSE
IF-ELSE Statement
if ( boolean_expression)
statement;
else
statement;
true false
boolean_expr
if ( boolean_expression) {
statement1;
statement2;
……………
} statement statement
else {
statement1;
statement2;
……………..
}
Nested IF-ELSE Statement
true false
boolean_expr
true false
statement1 boolean_expr
statement2 statement3
Switch Statement
switch(switch_expr) {
case case_selector1:
statement1;
statement2; Case_selector1 Block 1 statements Break;
……….
break;
case case_selector2:
Case_selector2 Block 2 statements Break;
statement1;
statement2;
……….
break;
Case_selector3 Block 3 statements Break;
default:
statement1;
statement2; default block
statements
……….
break;
}
Example: Decision
(Conditional Statements)
Given a score number, write a program that outputs the
grading system. If student has a score above 85, the program
outputs “A “. If the score is between 70 and 84 the program
outputs “B”. If the score is between 55 and 69 the program
outputs “C”. If the score is between 40 and 54 the program
outputs “D”. Otherwise, the program outputs “E”.
You need to use Conditional Statement
Repetition (Loop)
Repeat sections of code
Have terminating conditions
While loop
• Code will be executed while condition is TRUE
While(boolean_expr){ •The conditional is checked before loop execution
statement1; •Pre-checked Loop
statement2;
………. int i = 0;
} while (i <= 5){
System.out.print(i);
i++;
}
do-while loop
do{ Post-Checked Loop:
The body will always be executed at least once
statement1;
statement2;
………… int x = 0;
} while(boolean_expr); do
{
System.out.print(x);
x++;
} while(x<10);
For loop
• Code will be executed while condition is TRUE
•The conditional is checked before loop execution
for(InitializationExpression; LoopCondition; •Pre-checked Loop
StepExpression){ •Code in the loop is executed according to
the initializer, conditional & updater
statement1;
statement2;
int i;
…………. for( i = 0; i < 10; i++){
} System.out.print(i);
}