1
Control Structure
Introduction to Programming 1
2
Objectives
At the end of the lesson, the student should be able to:
● Use decision control structures (if, else, switch) which allows
selection of specific sections of code to be executed
● Use repetition control structures (while, do-while, for) which
allow executing specific sections of code a number of times
● Use branching statements (break, continue, return) which
allows redirection of program flow
Introduction to Programming 1
3
Control Structures
● Control structures
– allows us to change the ordering of how the statements in our
programs are executed
● Two types of Control Structures
– decision control structures
● allows us to select specific sections of code to be executed
– repetition control structures
● allows us to execute specific sections of the code a number of times
Introduction to Programming 1
4
Decision Control Structures
● Decision control structures
– Java statements that allows us to select and execute specific blocks
of code while skipping other sections
● Types:
–
if-statement
–
if-else-statement
–
If-else if-statement
Introduction to Programming 1
5
if-statement
●
if-statement
– specifies that a statement (or block of code) will be executed if and
only if a certain boolean statement is true.
●
if-statement has the form:
if( boolean_expression )
statement;
or
if( boolean_expression ){
statement1;
statement2;
}
– where,
● boolean_expression is either a boolean expression or boolean variable.
Introduction to Programming 1
6
if-statement Flowchart
Introduction to Programming 1
7
Example 1
int grade = 68;
if( grade > 60 )
System.out.println("Congratulations!");
Introduction to Programming 1
8
Example 2
int grade = 68;
if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println("You passed!");
}
Introduction to Programming 1
9
Coding Guidelines
1. The boolean_expression part of a statement should
evaluate to a boolean value. That means that the execution
of the condition should either result t