COM 413 Lesson 3
COM 413 Lesson 3
Lesson 3:
Control Structures / Statements
Directs the flow of execution in a program.
Control structures enable the programmer to achieve iteration and branching.
i. if statement
ii. if ... else statement
iii. nested if … else statement
iv. switch case statement
Looping Control structures
Facilitate the action of repetition / iteration
Examples:
i. for loop
ii. do … while loop
iii. while loop
Jumping Control Structures
Examples:
i. break statement
ii. continue statement
If control structure
Control structure that considers only the true part of the condition;
Syntax:
Example 1;
if(condition) T
Statement;
Example 2
if(condition)
{
Statement;
Statement;
Statement;
}
Cont’d …
Program example (if control statement)
if(condition)
{
Statement; TP
Statement;
}
else
{
statement; FP
Statement;
}
Cont’d …
Program demo (if .. else)
statement
else if(cond)
statement
else if(cond)
statement;
else
statement;
Cont’d …
Program demo for nested if … else
Write a program that reads the name and the marks scored by a
student, and to display the corresponding grade:
Use the given grading system:
The break statement in each of the cases transfers the control of execution
outside the switch control structure.
The default option handles any mismatch in the control structure.
Program demo for switch case:
Write a menu driven program to preform the following:
Compute the perimeter of a rectangle
Compute the sum of two numbers
Ie: *131#
Main menu
1. perimeter
2. sum
Enter your choice
Looping control structures
Syntax:
F
do… while loop (syntax)
Statement;
do
{
Statement;
Statement;
statement;
}
while(cond);
Statement;
Demo programs using do… while loop
COND
The condition is checked before
executing the block of code. T
Syntax:
while(cond)
BLOCK
{
statement;
statement;
}
Demo programs using while loop
T
Cond break
Normal F
Loop
//break demo program
public BreakDemo() {
public class BreakDemo {
void checkNumber() { }
for(int i=0;i<10;i++)
public static void main(String[] args) {
{
if(i==8) BreakDemo bd = new
break; BreakDemo();
System.out.println(" " +i);
} bd.checkNumber();
} }
}
Continue control structure