W6-Presentation02-Control Structures
W6-Presentation02-Control Structures
• if Statement
- enables the program to execute a statement or block of
codes if and only if the boolean expression is true.
The if-statement is can be express this form,
if (boolean_expression)
statement;
or
If (boolean_expression){
statement1;
statement2;
...
}
The figure below shows the execution flow of the if statement:
Boolean Expression
true false
Statement
For example:
if(age>=18)
System.out.println("Qualified to vote!");
Output:
Coding Guidelines:
1.Using if-statement without curly braces makes the code shorter, but it is prone to
errors and hard to read.
2.You should indent the statements inside the block, for example:
if( boolean_expression ){
//statement1;
//statement2;
}
3. Inside the block you can put any statement, meaning you have another if
statement inside the if statement, fir example:
if(boolean_expression){
if (boolean_expression){
//Statements
}
}
• if-else Statement
-is used when you want the program decide from which of the
two sets of statements is going to be executed based on whether the
condition is true or false.
The if-else statement has the form,
if( boolean_expression )
statement;
else
statement;
or can also be written as,
if( boolean_expression ){
statement1;
statement2;
...
}
else{
statement1;
statement2;
...
}
Below is the flowchart for if-else statement:
if(age>=18)
System.out.println("Qualified to vote!");
else
System.out.println("To young to vote!");
Below is the flowchart for the sample code above:
if( boolean_expression ){
statement1;
statement2;
...
}
else{
if( boolean_expression ){
statement1;
statement2;
...
}
}
we usually write this as:
if( boolean_expression ){
statement1;
statement2;
...
}
else if( boolean_expression ){
statement1;
statement2;
...
}
Below is the flowchart for if-else if-else statement:
switch( switch_expression ){
case case_value1:
// statements
break;
case case_value2:
// statements
break;
...
case case_valueN:
// statements
break;
default:
//statements
}
For example:
int num = 2;
switch(num){
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
case 4:
System.out.println("Four");
break;
default:
System.out.println("Invalid Number");
}
Below is the flowchart of the example above:
Sample switch Statement Program: