0% found this document useful (0 votes)
25 views57 pages

Chapter 2 Expression Flow

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views57 pages

Chapter 2 Expression Flow

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 57

ISB 16003 Object Oriented

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

• Recall the three basic control structures


– Sequence
– Selection
– Repetition
• Selection enables the program flow to deviate from
sequence when certain conditions are true
• Selection allows programs to make decisions
The if Statement

int testScore;

testScore = //get test score input

if (testScore < 70)


This
Thisstatement
statementisis
JOptionPane.showMessageDialog(null, executed
executedififthe
thetestScore
testScore
isisless than 70.
less than 70.
"You did not pass" );

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.

if (testScore >= 70) {


if (studentAge < 10) {
System.out.println("You did a great job");
} else {
System.out.println("You did pass"); //test score >=
70
} //and age >= 10
} else { //test score < 70
System.out.println("You did not pass");
}
Control Flow of Nested-if
Statement
true inner if
false testScore
testScore>=
>=70
70
??

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

Test Score Grade


90  score A
80  score  90 B
70  score  80 C
60  score  70 D
score  60 F
The switch Statement
int gradeLevel;
gradeLevel = JOptionPane.showInputDialog("Grade (Frosh-1,Soph-2,...):" );

switch (gradeLevel) {
This
Thisstatement
statement
isisexecuted
executedifif
case 1: System.out.print("Go to the Gymnasium"); the
thegradeLevel
gradeLevel
break; isisequal
equaltoto1.1.

case 2: System.out.print("Go to the Science Auditorium");


break;

case 3: System.out.print("Go to Harris Hall Rm A3");


break;
This
Thisstatement
statement
isisexecuted
executedifif
case 4: System.out.print("Go to Bolt Hall Rm 101"); the
thegradeLevel
gradeLevel
break; isisequal
equaltoto4.4.
}
Syntax for the switch
Statement
switch ( <arithmetic expression> ) {
<case label 1> : <case body 1>

<case label n> : <case body n>
}
Arithmetic
ArithmeticExpression
Expression
switch ( gradeLevel ) {
case 1: System.out.print("Go to the Gymnasium");
break;
Case
Case
Label
Label case 2: System.out.print("Go to the Science Auditorium");
break;
case 3: System.out.print("Go to Harris Hall Rm A3");
Case
Case
break;
Body
Body
case 4: System.out.print("Go to Bolt Hall Rm 101");
break;
}
switch With No break
Statements
true
NN ==
==
11?? xx==10;
10;
switch ( N ) {
case 1: x = 10; false
true
case 2: x = 20; NN ==
==
22?? xx==20;
20;
case 3: x = 30;
} false
true
NN ==
== xx==30;
30;
33??

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;

default: System.out.print("Input error: Invalid Data");


break;
}
Objectives -2

In this chapter you also will:


• Learn about the three types of repetition control
structures
• Learn how to use the while, for, and do…while
statements to repeat program code
• Explore how to create nested loops and perform multiple
levels of repetition
• Learn how to use the break and continue
statements to exit loops
Repeating Program
Statements
• Three basic program structures: sequence, selection and repetition
• Two types of conditions
– Conditions using logical expressions
– Conditions using integral expressions
• This chapter focuses on repetition structures using logical conditions
– while loops
– for loops
– do…while loops
The while Statement

• while statement syntax:


while (condition){
action
}
• The condition is called a pretest condition
• The code between the braces is the loop body
• Iteration: A single execution of the loop body
• If condition is never false, loop never terminates
Flowchart for a while Loop
Counter-Controlled while
Loops
• A loop control variable controls the number of times a loop is executed
• A loop control variable is also called a counter variable
• A termination constant contains the number of times the loop should
execute
• A termination condition is the condition that the loop control variable is
less than the termination constant
Counter-Controlled while
Loops (continued)
int i = 0; is the
counter variable
int N = 5; is the
termination constant
(i < N) is the
termination condition
The loop terminates
when the i equals 5
(N)
Sentinel-Controlled while
Loops
• A sentinel is a special value that signals the end of a loop
• Does not need a loop counter
• Loop counters may be useful for other purposes
Sentinel-Controlled while
Loops (continued)

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;

for (i = 0; i < 20; i++) {

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

for ( i = 0 ; i < 20 ; i++ ) {

number = scanner.nextInt(); Statement


Statement
sum += number; (loop
(loopbody)
body)
}
Control Flow of for

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

for (int i = 1; i <= 5; i++)


{
for (int j = 1; j <= 4; j++)
INNE
OUTE

System.out.print("("+i+","+j+")");
R
R

System.out.println();
}
Generating the Table using
Nested Loop

for (int i = 1; i <= 5; i++)


{
for (int j = 1; j <= 4; j++)
INNE
OUTE

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

Increment the counter


The do…while Statement
• We have seen the while loop
• We have seen the for loop
• The for loop is logically equivalent to the counter-controlled while loop
• Next: The do…while loop
The do…while Statement’s
Syntax
• Recall the while loop syntax:
while (condition) {
action
}
• It is possible the loop body never executes
• If the condition is false, the loop ends
The do…while
Statement’s Syntax
(continued)
• The do…while syntax:
do{
action
}while (condition)
• The loop body must execute at least once
• After the first execution of the loop body, the condition is tested
• The condition is also called a posttest condition
The do…while Flowchart
A do…while Example
The menu will be
presented at least once

A switch statement
allows a choice of options

Loop terminates when


user enters 4
Loop-and-a-Half Repetition
Control
• Loop-and-a-half repetition control can be used to test a loop’s terminating
condition in the middle of the loop body.

• It is implemented by using reserved words while, if, and break.


Nested Loops,
break, and continue
• Recall previous topic presented nested if statements
• Recall that switch statements are equivalent to nested if statements
• Recall that break was used to exit early from a switch structure
• Next: Nested loops, break and continue statements in loops
Example: Loop-and-a-Half
Control
String name;

while (true){

name = JOptionPane.showInputDialog(null, "Your name");

if (name.length() > 0) break;

JOptionPane.showMessageDialog(null, "Invalid Entry." +


"You must enter at least one character.");
}
The break Statement in Loops
• The break statement in a switch statement ensured that the switch
exited after a particular case was executed
• A break statement in a loop causes that particular loop to terminate
• A break statement can be used in any kind of loop
The break Statement in Loops
(continued)

The loop terminates


(unfinished) when i == 5
The continue Statement
• The continue statement
causes the current loop iteration
to be skipped

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

• Sequence structures perform program statements in the


order they are presented
• Selection allows program flow to branch to one or more
alternatives based on a condition
• A logical (Boolean) expression uses variables or literals,
and relational or logical operators
• A relational operator compares two numbers
• Strings are compared using methods from the String
class
Summary (continued)

• Three methods of comparing strings are equals,


equalsIgnoreCase, and compareTo
• Three logical (Boolean) operators: ! (not), && (and) and
|| (or)
• One-way selection uses an if statement
• Two-way selection uses an if…else statement
• Nested if…else and switch statements allow more
than two alternatives
Summary (continued)
• Three basic repetition structures in Java
– while loops
– for loops
– do…while loops
• The syntax of a while loop is
while (condition) {
action
}
Summary (continued)
• The condition is a Boolean expression, and the loop body executes until
the condition is false
• A counter-controlled while loop uses a counter variable
• A sentinel-controlled while loop uses a variable and a fixed sentinel
value
• A for loop is logically equivalent to a counter-controlled while loop
Summary (continued)
• The syntax of a for loop is
for (counter initialization;termination
condition;increment/decrement){
action
}
• The syntax of a do…while loop is
do {
action
} while (condition)
Summary (continued)
• In a do…while loop, the action is executed at least once
• A nested loop is a loop inside a loop
• Any type of loop and any number of loops can be nested
• A break statement causes the current loop to exit early
• A continue statement causes the current iteration of a loop to be
skipped
EXERCISE
Consider the following questions,
where i is an int variable
1. for (i = 10; i <= 9; i++) NOT EXECUTE
System.out.println(i + “ ");

2. for (i = 10; i <= 10; i++)


System.out.print(I + “ "); once
System.out.println(“ ");

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("*");

You might also like