Chapter 2 Expression Flow
Chapter 2 Expression Flow
Programming
Chapter 2
Expression and
Flow Control
Prepared by :
Puan Robiah Hamzah
Objectives -1
In this chapter you will:
• Learn about the three basic programming control
structures
• Use Java to compare numbers using relational operators
• Explore how to apply logical operators to form complex
logical expressions
• Learn how to use if…else and switch statements to
make decisions in programs
Making Decisions with Java
• Three types of control structures
– Sequence structure performs a series of steps
– Selection structure makes decisions based on certain conditions
– Repetition structure repeats a sequence under certain conditions
• Selection structure decides on two or more alternatives using if and
else keywords
• All selections have a comparison between two numbers or strings
Comparing Numbers in Java
• Eight primitive data types
– byte, short, int, long, float, double, char, boolean
• Comparing numbers in Java is to compare values of numeric primitives
• First step in making decisions is forming a logical expression
• Logical expressions are either true or false
Relational Operators
• Logical expressions involve one or more variables (or literals) and one or
more relational operators
• A relational operator is a symbol in a logical expression to compare two
values
• Relational operators compare two numeric primitives
Relational Operators
(continued)
Relational Example
Value of Example
Operator Let x=5, y=20
== x == y false
!= x != y true
< x < y true
> x > y false
<= x <= y true
>= x >= y false
Selection Structures in Java
int testScore;
else
This
Thisstatement
statementisis
JOptionPane.showMessageDialog(null, executed
executedififthe
thetestScore
testScore
isis70 or higher.
70 or higher.
"You did pass" );
Syntax for the if Statement
if ( <boolean expression> )
<then block>
else
Boolean
BooleanExpression
Expression
<else block>
if ( testScore < 70 )
Then
ThenBlock
Block JOptionPane.showMessageDialog(null,
"You did not pass" );
else
Else
ElseBlock
Block JOptionPane.showMessageDialog(null,
"You did pass " );
The Nested-if Statement
• The then and else block of an if statement can contain any valid statements,
including other if statements. An if statement containing another if
statement is called a nested-if statement.
messageBox.show
messageBox.show
false studentAge
studentAge<<10
10
true
("You
("Youdid
didnot
not ??
pass");
pass");
messageBox.show
messageBox.show
messageBox.show
messageBox.show ("You
("Youdid
didaagreat
great
("You
("Youdid
didpass");
pass"); job");
job");
if – else if Control
switch (gradeLevel) {
This
Thisstatement
statement
isisexecuted
executedifif
case 1: System.out.print("Go to the Gymnasium"); the
thegradeLevel
gradeLevel
break; isisequal
equaltoto1.1.
false
switch With break Statements
true
NN ==
==
11?? xx==10;
10;
false break;
break;
true
NN ==
==
22?? xx==20;
20;
false break;
break;
true
NN ==
==
33?? xx==30;
30;
false break;
break;
switch With the default Block
switch (ranking) {
case 10:
case 9:
case 8: System.out.print("Master");
break;
case 7:
case 6: System.out.print("Journeyman");
break;
case 5:
case 4: System.out.print("Apprentice");
break;
Sentinel variable
entered by the user
The for Statement
• Two kinds of while loops
– Counter-controlled – know exactly how many times
statement need to be executed
– Sentinel-controlled- don’t know how many times to be
executed but need to executed until special value met
• The while loop is the most general repetition structure
• The for loop is logically equivalent to the counter-controlled while loop
The for Statement
int i, sum = 0, number;
number = scanner.nextInt( );
sum += number;
}
These
Thesestatements
statementsare are
executed for 20
executed for 20 times times
((i i==0,0,1,1,2,2,…
…, ,19).
19).
Syntax for the for Statement
for ( <initialization>; <boolean expression>; <increment> )
<statement>
Boolean
Boolean
Initialization
Initialization Increment
Increment
Expression
Expression
i i==0;
0;
i i<<20
20??
false
true
number
number ==. .. .. .; ;
sum
sum +=+=number;
number;
i i++;
++;
More for Loop Examples
i i==0,
0,5,
5,10,
10,…
…,,95
95
j j==2,
2,4,
4,8,
8,16,
16,32
32
kk==100,
100,99,
99,98,
98,97,
97,...,
...,11
Generating the Table using
Nested Loop
INNE
OUTE
R
R
Generating the Table using
Nested Loop
System.out.print("("+i+","+j+")");
R
R
System.out.println();
}
Generating the Table using
Nested Loop
System.out.print("(” * ");
R
R
System.out.println();
}
Output:
****
****
****
****
****
Nested Control Structures
(Example)
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
System.out.print(" *");
System.out.println();
}
• Output:
*
**
***
****
*****
The for Statement’s Syntax
(continued)
Declare and initialize the
counter variable
Termination condition
A switch statement
allows a choice of options
while (true){
If break were
replaced by
continue, i == 5
would be skipped.
The continue statement can be used with
any type of loop
A Caveat About
break and continue
• Some programmers prefer to avoid break and continue because they
make the program harder to understand
• Some programmers feel break and continue are useful in some
situations
• Best to use sparingly, especially if the loop can be written to avoid them
Summary
3. for (i = 1; ; i++)
System.out.print(I + “ "); Infinite
System.out.println(“ "); loop
The for Looping (Repetition)
Structure (continued)
Example
1. The following for loop outputs the word Hello and a star (on separate
lines) five times:
for (i = 1; i <= 5; i++)
{
System.out.println("Hello");
System.out.println("*");
}
2.
for (i = 1; i <= 5; i++)
System.out.println("Hello");
System.out.println("*");
This loop outputs the word Hello five times and the star only once
The for Looping (Repetition)
Structure (continued)
3. Write a for statement , to executes five empty statement
for (i = 1; i < 5; i++);
System.out.println("*");