You are on page 1of 2

Computer Programming 2

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
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
If - statement
specifies that a statement or block of code! will be executed if and only if a certain "oolean statement is true#
if-statement has the form: where$ boolean%expression is either a boolean expression or
boolean variable#
if boolean%expression ! if-statement Flowchart
statement&
or
if boolean%expression !'
statement(&
statement)&
*
Example
int grade + ,-&
if grade . ,/ !
0ystem#out#println12ongratulations31!&
If - else statement
used when we want to execute a certain statement if a condition is true$ and a different statement if the
condition is false#
if-else statement has the form: if-else statement Flowchart Example
if boolean%expression !'
statement(&
statement)&
# # #
*
else'
statement4&
statement5&
# # #
*
If - else - elseif statement
The statement in the else-clause of an if-else block can be another if-else structures#
( | C S 2 0 2 C ! Computer Programming 2
6 e r c i v a l 7 # 8 e r n a n d e 9
int grade + ,-&
if grade . ,/ !
0ystem#out#println12ongratulations31!&
else
0ystem#out#println10orry you failed1!&
This cascading of structures allows us to make more complex selections#
The statement has the form: Example
if boolean%expression( !
statement(&
else if boolean%expression) !
statement)&
else
statement4&
if elseif - else
statement Flowchart
Switc" - statement
switch allows branching on multiple outcomes#
switch statement has the form:
switch switch%expression !'
case case%selector(:
statement(&::
statement)&::block (
break&
case case%selector):
statement(&::
statement)&::block ) Example
break&
:
default:
statement(&::
statement)&::block n
*
) | C S 2 0 2 C ! Computer Programming 2
6 e r c i v a l 7 # 8 e r n a n d e 9
int grade + ,-&
if grade . ;/ !' 0ystem#out#println1<ery good31!& *
else if grade . ,/ !' 0ystem#out#println1<ery good31!& *
else' 0ystem#out#println10orry you failed1!& *
where$
switch_expression
is an integer or character expression
case_selector1,case_selector2 and so on,
are uni=ue integer or character constants#
public class >rade '
public static void main 0tring?@ args !
'
int grade + ;)&
switchgrade!'
case (//: 0ystem#out#println 1Axcellent31 !& break&
case ;/: 0ystem#out#println1>ood Bob31 !& break&
case -/: 0ystem#out#println10tudy harder31 !& break&
default: 0ystem#out#println10orry$ you failed#1!&
*
* *

You might also like