Chapter 3: Control
Structures
Object Oriented Programming
Learn about control structures
Examine relational and logical operators
Explore how to form and evaluate logical (Boolean)
expressions
Learn how to use the selection control structures if, if…else,
Learning and switch in a program
Objectives Learn about repetition (looping) control structures
Explore how to construct and use count-controlled, sentinel-
controlled, flag-controlled, and EOF-controlled repetition
structures
Examine break and continue statements
Discover how to form and use nested control structures
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 2
Control Structures I:
Selection
Three methods of processing a program
− In sequence
− Branching
Control − Looping
Structures Branch: altering the flow of program execution by making a
selection or choice
Loop: altering the flow of program execution by repetition of
statement(s)
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 4
Flow of
Execution
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 5
Relational Operator
− Allows you to make comparisons in a program
Relational − Binary operator
Operators Condition is represented by a logical expression in Java
Logical expression: expression that has a value of either true
or false
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 6
Relational
Operators in
Java
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 7
Relational Can be used with integral and floating-point data types
Operators and Can be used with the char data type
Primitive Data Unicode Collating Sequence
Types
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 8
Relational
Operators and
the Unicode
Collating
Sequence
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 9
class String
− Method compareTo
− Method equals
Given string str1 and str2
Comparing
Strings an integer 0 if string str1 str2
[Link](str2)= 0 if string str1 is equal to string str2
an integer 0 if string str1 str2
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 10
Comparing
Strings
String str1 = "Hello";
String str2 = "Hi";
String str3 = "Air";
String str4 = "Bill";
String str5 = "Bigger";
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 11
Comparing
Strings
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 12
Comparing
Strings
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 13
Logical
(Boolean)
Operators
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 14
Logical
(Boolean)
Operators
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 15
Logical
(Boolean)
Operators
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 16
Logical
(Boolean)
Operators
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 17
Precedence of
Operators
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 18
Short-Circuit Definition: a process in which the computer evaluates a
logical expression from left to right and stops as soon as the
Evaluation value of the expression is known
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 19
One-Way Selection
Two-Way Selection
Compound (Block of) Statements
Selection Multiple Selections (Nested if)
Conditional Operator
switch Structures
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 20
Syntax:
− if (expression)
statement
One-Way
Expression referred to as decision
Selection maker
Statement referred to as action
statement
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 21
//Program to determine the absolute value of an integer
import [Link];
public class AbsoluteValue
{
public static void main(String[] args)
{
One-Way int number;
Selection int temp;
String numString;
numString =
[Link]
("Enter an integer:"); //Line 1
number = [Link](numString); //Line 2
temp = number; //Line 3
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 22
if (number < 0) //Line 4
number = -number; //Line 5
[Link](null,
One-Way "The absolute value of " + temp
+ " is " + number,
Selection "Absolute Value",
JOptionPane.INFORMATION_MESSAGE); //Line 6
[Link](0);
}
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 23
Syntax:
− if (expression)
Two-Way else
statement1
Selection statement2
else statement must be paired
with an if
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 24
if (hours > 40.0); //Line 1
wages = 40.0 * rate +
1.5 * rate * (hours - 40.0); //Line 2
else //Line 3
wages = hours * rate; //Line 4
Two-Way Because a semicolon follows the closing parenthesis of the
Selection if statement (Line 1), the else statement stands alone
The semicolon at the end of the if statement (see Line 1)
ends the if statement, so the statement at Line 2 separates
the else clause from the if statement; that is, else is by itself
Since there is no separate else statement in Java, this code
generates a syntax error
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 25
Syntax
Compound
(Block of)
Statements
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 26
if (age > 18)
{
[Link]("Eligible to vote.");
Compound }
[Link]("No longer a minor.");
(Block of) else
Statements {
[Link]("Not eligible to vote.");
[Link]("Still a minor.");
}
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 27
Syntax Else associated with most recent
− if (expression1)
Multiple statement1
incomplete if
Multiple if statements can be
Selection: else if (expression2)
used in place of if…else
statement2
Nested if else
statements
statement3
May take longer to evaluate
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 28
Ternary operator
Syntax
Conditional (? :) − expression1 ? expression2 : expression3
Operator If expression1 = true, then the result of the condition is
expression 2; otherwise, the result of the condition is
expression3
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 29
Switch
Structures
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 30
In Java, switch, case, break, and default are reserved words
In a switch structure, the expression is evaluated first
The value of the expression is then used to perform the
Switch actions specified in the statements that follow the reserved
Structures word case
The expression is usually an identifier
The value of the identifier or the expression can be only
integral, that is, an integer
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 31
Integral values also include values of type char
The expression is sometimes called the selector; its value
determines which statements are selected for execution
Switch
A particular case value must appear only once
Structures
One or more statements may follow a case label, so you do
not need to use braces to turn multiple statements into a
single compound statement
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 32
The break statement may or may
not appear after each
Switch statements1, statements2, ...,
statementsn
Structures A switch structure may or may not
have the default label
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 33
Switch
Structures
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 34
switch (grade)
{
case 'A':
[Link]("The grade is A.");
break;
Switch case 'B':
Structures [Link]("The grade is B.");
break;
case 'C':
[Link]("The grade is C.");
break;
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 35
case 'D':
[Link]("The grade is D.");
break;
Switch case 'F':
[Link]("The grade is F.");
Structures break;
default:
[Link]("The grade is invalid.");
}
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 36
Programming Input: customer’s account number, customer code, number
Example: of premium channels to which customer subscribes, number
of basic service connections (in case of business customers)
Cable Company
Output: customer’s account number and the billing amount
Billing
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 37
Programming Solution:
Example: − Prompt user for information
− Use switch statements based on customer’s type
Cable Company − Use an if statement nested within switch statement to determine
Billing amount due by each customer
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 38
Control Structures II:
Iteration
Why Is There are many situations in which the same statements
need to be executed several times
Repetition Example
Needed? − Formulas used to find average grades for students in a class
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 40
Syntax
The while − while (expression)
statement
Looping
Expression is always true in an
(Repetition) infinite loop
Structure Statements must change value of
expression to false
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 41
i = 0; //Line 1
while (i <= 20) //Line 2
{
[Link](i + " "); //Line 3
The while i = i + 5; //Line 4
Looping }
(Repetition) [Link](); //Line 5
Structure
Output:
0 5 10 15 20
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 42
Typically, while loops are written in the following form:
The while
Looping
(Repetition)
Structure
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 43
Used when exact number of data or entry pieces is known
General form:
Counter-
Controlled while
Loop
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 44
Used when exact number of entry pieces is unknown but
last entry (special/sentinel value) is known
General form:
Sentinel-
Controlled while
Loop
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 45
Boolean value used to control loop
General form:
Flag-Controlled
while Loop
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 46
Used when input is from files
Sentinel value is not always appropriate
EOF(End of In an EOF-controlled while loop that uses the Scanner object
File)-Controlled console to input data, console acts at the loop control
variable
while Loop The method hasNext, of the class Scanner, returns true if
there is an input in the input stream; otherwise it returns
false
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 47
The expression [Link]() evaluates to true if there
is an input in the input stream; otherwise it returns false
Expressions such as [Link]() act as the loop
condition
EOF(End of A general form of the EOF-controlled while loop that uses the
File)-Controlled Scanner object console to input data is of the form:
while Loop
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 48
Suppose that inFile is a Scanner object initialized to the
input file; in this case, the EOF-controlled while loop takes
EOF(End of the following form:
File)-Controlled
while Loop
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 49
Programming Input file: customer’s account number, account balance at
Example: beginning of month, transaction type (withdrawal, deposit,
interest), transaction amount
Checking Output: account number, beginning balance, ending
Account balance, total interest paid, total amount deposited, number
Balance of deposits, total amount withdrawn, number of withdrawals
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 50
Programming Solution
Example: − Read data
− EOF-controlled loop
Checking − switch structure of transaction types
Account − Determine action (add to balance or subtract from balance
depending on transaction type)
Balance
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 51
Fibonacci formula for any Fibonacci sequence:
− an = an-1 + an-2
Programming Input: first two Fibonacci numbers in sequence, position in
Example: sequence of desired Fibonacci number (n)
Fibonacci − int previous1 = Fibonacci number 1
− int previous2 = Fibonacci number 2
Number − int nthFibonacci = position of nth Fibonacci number
Output: nth Fibonacci number
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 52
if (nthFibonacci == 1)
current = previous1;
else if (nthFibonacci == 2)
current = previous2;
else
Programming {
counter = 3;
Example: while (counter <= nthFibonacci)
Fibonacci {
current = previous2 + previous1;
Number previous1 = previous2;
previous2 = current;
counter++;
}
}
Final result found in last value of current
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 53
Specialized form of while loop
The for Looping Simplifies the writing of count-controlled loops
(Repetition) Syntax:
Structure − for (initial expression; logical expression; update expression)
statement
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 54
Execution
− Initial statement executes
The for Looping − The loop condition evaluated
(Repetition) − If loop condition evaluates to
true, execute for loop statement
Structure and execute update statement
− Repeat until loop condition is
false
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 55
The following for loop prints the first 10 nonnegative
integers:
The for Looping
(Repetition) for (i = 0; i < 10; i++)
Structure [Link](i + " ");
[Link]();
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 56
The following for loop outputs the word Hello and a star (on
separate lines) five times:
for (i = 1; i <= 5; i++)
{
[Link]("Hello");
The for Looping }
[Link]("*");
(Repetition) This loop outputs the word Hello five times and the star only
Structure once
for (i = 1; i <= 5; i++)
[Link]("Hello");
[Link]("*");
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 57
Does not execute if initial condition is false
Update expression changes value of loop control variable,
eventually making it false
The for Looping If logical expression is always true, result is an infinite loop
(Repetition) Infinite loop can be specified by omitting all three control
Structure statements
If logical expression is omitted, it is assumed to be true
for statement ending in semicolon is empty
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 58
Programming Input: N integers (positive, negative, and zeros)
− int N = 20; //N easily modified
Example: Output: number of 0s, number of even integers, number of
Classify odd integers
Numbers
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 59
for (counter = 1; counter <= N; counter++)
{
number = [Link]();
[Link](number + " ");
Programming switch (number % 2)
{
Example: case 0:
evens++;
Classify if (number == 0)
zeros++;
Numbers break;
case 1:
case -1:
odds++;
} //end switch
} //end for loop
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 60
Syntax:
The do…while
Loop
(Repetition)
Structure Statements executed first, then logical expression evaluated
Statement(s) executed at least once then continued if logical
expression is true
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 61
do…while Loop
(Post-test Loop)
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 62
Used to exit early from a loop
break Used to skip remainder of switch structure
Statements Can be placed within if statement of a loop
If condition is met, loop exited immediately
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 63
Used in while, for, and do...while structures
When executed in a loop, the remaining statements in the
loop are skipped; proceeds with the next iteration of the loop
continue
When executed in a while/do…while structure, expression
Statements evaluated immediately after continue statement
In a for structure, the update expression is executed after
the continue statement; then the loop condition executes
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 64
Provides new power, subtlety, and complexity
Nested Control if, if…else, and switch structures can be placed within while
Structures loops
for loops can be found within other for loops
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 65
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
[Link](" *");
[Link]();
Nested Control }
Output:
Structures *
**
***
****
*****
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 66
Control structures are used to process programs
Logical expressions and order of precedence of operators
are used in expressions
Compare strings
Summary If statements
if…else statements
switch structures
Proper syntax for using control statements
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 67
Looping Mechanisms
− Counter-controlled while loop
− Sentinel-controlled while loop
− Flag-controlled while loop
− EOF-controlled while loop
Summary − for loop
− do…while loop
break statements
continue statements
Nested control structures
Engr. Kris C. Calpotura, MSME, MIT Chapter 3: Control Structures 68
The End!!!