Control structures - U of W ACS Homepage

Control Structures (Chapter 3)
3 constructs are essential building blocks for programs
• Sequences
 compound statement
• Decisions
 if, switch, conditional operator
• Loops
 while, do while, for, enhanced for
1
Control Structures
Order of topics:
• compound
• while
• autoincrement and autodecrement
Loops often use a programming idiom
• if
called autoincrement and autodecrement.
• for
• do-while
• switch
• conditional operator
2
Compound statement
A compound statement is a group of statements that are
executed sequentially, one following the other, from
beginning to end
Opening brace
{
temp = x;
x = y;
y = temp;
}
A compound statement is
often used with if’s, while’s
etc.
… to provide a group of
statements to be executed
repeatedly or conditionally.
Closing brace
3
Loops: while
While statement
executes a statement as long as some expression is true
while ( logical expression )
statement
Very common for this statement
to be a compound statement
4
Loops: while
How a while executes
5
Loops: while
while ( logical expression )
statement
A logical expression is an expression that evaluates true or false.
Suppose a, b, q, i, j are integers and found is boolean.
Examples of logical expressions:
a < b
a+5 >= q*3
a == b
a != b
found
a < b || b < c
found && i<100
i < 100 && j < 100
!found && i < 100
! found
6
Loops: while
Example 1 Page 70. Numbers0to9 displays the digits from 0 to 9
A code snippet:
int count = 0;
System.out.println("Numbers");
while ( count < 10 ){
System.out.println(count);
count = count + 1;
}
Start of compound statement
Executed repeatedly
until count is 10
Indented code – this is practice we will follow
How can you modify this code to display numbers from 9 down to 0?
7
Loops: while
Example 2 Page 72. DisplayDigits displays the digits of a
positive number.
A code snippet:
Start of compound statement
while (number > 0){
int digit = number % 10;
System.out.print("\t"+digit);
number = number / 10;
System.out.println("\t"+number);
}
Executed repeatedly as
long as number > 0
Indented code – this is practice we will follow
How can you modify this code to calculate the sum of an integer’s digits?
8
Loops: Nesting whiles
A while can contain another while
Example. Suppose we need to display a times table
(See example 3 page 72)
1
2
3
4
1
1
2
3
4
2
2
4
6
8
3
3
6
9
12
4
4
8
12
16
9
Loops: Nesting whiles
To produce a times table its best to use one loop inside
another.
We say one loop is nested inside the other loop.
To begin: we will just produce a simple vertical listing of
i, j, i*j
where i varies from 1 to 4 and j varies from 1 to 4.
Ultimately we want a listing like that shown on
previous slide.
see Example 3 on page 74 … shown on next slide
see Exercise 14 on page 77
10
Loops: Nesting whiles
public class NestedWhiles
For each value of i,
j takes on values 1, 2, 3, 4
{
public static void main(String[] args)
{
int i, j;
System.out.println("\ti\tj\ti*j");
// i takes on values 1,2,3,4
One while nested inside
i = 1;
another while
while (i < 5){
j = 1;
// j takes on values 1,2,3,4
while (j < 5){
System.out.println("\t"+i+"\t"+j+"\t"+(i*j));
j = j + 1;
}
i = i + 1;
}
System.out.println("program ended");
}
}
11
Loops: Nesting whiles
Output from NestedWhiles
Heading
Note when i is 1
when i is 2
when i is 3
when i is 4
j takes on 1, 2, 3, 4
j takes on 1, 2, 3, 4
j takes on 1, 2, 3, 4
j takes on 1, 2, 3, 4
12
Loops and Autoincrement, Autodecrement
statements such as
n = n + 1;
m = m - 1;
are so common in programming that languages such as
Java include special operators for this purpose called
autoincrement and autodecrement
13
Autoincrement and Autodecrement
n++;
m--;
and
++ n;
--m;
post-increment
post-decrement
pre-increment
pre-decrement
14
Autoincrement and Autodecrement
n++;
++ n;
When autoincrement is used alone and not
as part of a larger expression pre- and postincrement have the same effect … to
increment the operand by 1.
m--;
--m;
Similarily ….
When autodecrement is used alone and not
as part of a larger expression pre- and postdecrement have the same effect … to
decrement the operand by 1.
15
ASIDE: for Autoincrement and Autodecrement
ASIDE: autoincrement, autodecrement within an expression…
post-increment and post-decrement: the operand’s value is used
and then the operand’s value is incremented/ decremented
pre-increment and pre-decrement: the operand’s value is
incremented/ decremented and then the operand’s value is used
// try this out
// what is printed?
int m = 1;
int n = m++ + m++;
System.out.println("m="+m);
System.out.println("n="+n);
// try this out
// what is printed?
int m = 1;
int n = ++m + ++m;
System.out.println("m="+m);
System.out.println("n="+n);
16
Decision structures : the if statement
An if statement is coded with a logical expression and either
one statement (statement1)
or
two statements (statement1 and statement2)
written according to syntax as:
if ( logical expression)
statement1
else
statement2
The else clause is optional
We say the if is a decision structure … based on the outcome of
evaluating the logical expression one of possibly two statements
is executed.
17
Decision structures : the if statement
if ( logical expression)
statement1
else
The else clause is optional
statement2
When an if executes the logical expression is evaluated and :
•when the expression evaluates to true statement1 executes, and
then execution of program statements continue at the statement
following the if ;
•when the expression evaluates to false statement2 executes, and
then execution of program statements continue at the statement
following the if .
18
Decision structures : the if statement
Example. PositiveOrNot page 79
Gets a number from the user and displays positive or not positive
accordingly
int number = keyboard.nextInt();
System.out.print("the number "+number+" is ");
// Display a message if number is positive or not
if (number > 0) {
System.out.println("positive");
Only one of these
can execute
}
else {
System.out.println("not positive");
}
Strictly speaking, the { } are not required when there is just a single statement
… but it is a common practice to always use compound statements in control structures.
19
Decision structures : the if statement
Another example:
Background:
The Canadian SIN can be tested for a proper check digit.
Part of the process involves multiplying individual digits by either 1 or 2.
When a digit is multiplied by 2 and the result is greater than 9 then the two
digits of this product must be added.
For example, if the digit is 8 then the product 2*8 is 16. 16 is greater than 9
and so the sum of its digits is calculated  1+6 is 7
Along these lines consider a simpler program that:
1. gets a digit from the user
2. multiplies that digit by 2
3. if the product is <= 9 then displays the digit
otherwise displays the sum of the digits of the product
See next slide 
20
Decision structures : the if statement
import java.util.Scanner;
/**
* Get a digit from the user and multiply by 2
* If the result is larger than 9 add its two digits
*/
public class TestGreaterThanNine
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Please enter a single digit:");
int digit = kb.nextInt();
int result = digit*2;
if (result > 9) {
else clause is not necessary… and
result = result/10 + result%10;
so omitted
}
System.out.println(" result is "+result);
}
}
21
Decision structures : nested ifs
statement1 or statement2 can be any Java statement
statement1 , statement2 can be ifs, whiles, etc.
We can nest one control structure inside another control structure
22
Decision structures : nested ifs
Example. Round Cost Up Down
pages 82-83
Suppose we must handle a purchase transaction in one of two
ways:
• If the customer pays cash we must round up/down as there are
no pennies.
• If the customers pays by electronic means there is a surcharge
of 25 cents.
23
Decision structures : nested ifs
In pseudocode:
1. obtain the type and amount of the purchase
2. if the purchase is cash then round the cost up/down
3. otherwise add on the surcharge
4. display the total cost for the customer
Steps 2 and 3 can be handled with an if-else
Rounding up/down can be
handled with a nested if-else
Code for this is shown on next slide 
24
Decision structures : the if statement
if (typePayment.equals("cash")) {
if (originalCost % 5 < 3)
actualCost = originalCost - originalCost%5;
else
actualCost = originalCost + (5 - originalCost%5);
}
else
actualCost = originalCost + 25;
Nested if to handle
rounding for a cash payment
25
Decision structures : nested ifs
Example. Consider the example beginning on page 84
A table for converting alphabetic grades to a numeric value:
Letter grade
Numeric grade
A
4
B
3
C
2
D
1
F
0
When you need to convert some letter grade to its equivalent numeric
value you would look for which row the letter appears in and read off the
numeric value in that same row.
E.g. the numeric value corresponding to B is 3
26
Decision structures : nested ifs
To program this conversion nested ifs are useful
Letter grade
Numeric grade
A
4
B
3
C
2
D
1
F
0
We can structure this code in many ways
We will consider three ways to write the required logic 
27
Decision structures : nested ifs
Option 1:
if (letterGrade.equals("A"))
numericGrade = 4.0;
if (letterGrade.equals("B"))
numericGrade = 3.0;
if (letterGrade.equals("C"))
numericGrade = 2.0;
if (letterGrade.equals("D"))
numericGrade = 1.0;
This style requires the evaluation of expressions that would not be necessary (for
example, when the grade is A the other ifs do not need to execute, but they do)
28
Decision structures : nested ifs
Option 2:
if (letterGrade.equals("A"))
numericGrade = 4.0;
else
if (letterGrade.equals("B"))
numericGrade = 3.0;
else
if (letterGrade.equals("C"))
numericGrade = 2.0;
else
if (letterGrade.equals("D"))
numericGrade = 1.0;
else
numericGrade = 0.0;
This style uses indentation properly … each if is indented within the outer if
… but the code easily goes off the page/screen and gets hard to read
29
Decision structures : nested ifs
Option 3:
if (letterGrade.equals("A"))
numericGrade = 4.0;
else if (letterGrade.equals("B"))
numericGrade = 3.0;
else if (letterGrade.equals("C"))
numericGrade = 2.0;
else if (letterGrade.equals("D"))
numericGrade = 1.0;
else
numericGrade = 0.0;
Due to the similarity of the logical conditions, this style would be favoured by
many … it shows the choices at the same level of indentation
30
Loops: for
The for statement is commonly used where there is a need
for a statement to be executed a specific number of times
The syntax of the for statement we consider here is
for ( initialization; logical expression; increment )
statement
31
Loops: for
32
Loops: for
Example 1, Numbers0To9WithFor , uses a for to display integers 0 through 9
A code snippet:
Loop continues as
long as count < 10
for (int count=0; count < 10; count++ )
count starts at 0
System.out.println(count);
Increment
Count is increased by 1
each time through the loop
The statement that is executed repeatedly
This statement is indented for clarity and readability
33
Loops: for
Example 2, GetIndividualCharacters, uses charAt and a for.
Displays characters one-by-one.
A code snippet:
Length of the string
String text = "abc123";
int textLength = text.length();
System.out.println("text string is: "+text);
System.out.println("now, each character one-by-one");
for (int i=0; i<textLength; i++){
char c = text.charAt(i);
length used to control number
System.out.println(c);
of times loop executes
}
Get the ith character
Indented code
34
Loops: nesting control structures
Example 3, CountLetters, uses an if and a for.
Counts the number of times the letter ‘a’ appears.
A code snippet:
A line of text
length used to control number
of times loop executes
text = kb.nextLine();
int count = 0;
for (int i=0; i<text.length(); i++){
if (text.charAt(i) == 'a')
count++;
Use an if to test the ith character
}
System.out.println("The line contains "+count
+" a\'s");
35
Loops: nesting control structures
Example 4, NestedFor, uses two fors, one nested inside the other
Lines 10 to 13 …. the outer for
Lines 11 and 12 … the inner for
10
11
12
for (int i =1; i <=4; i ++) {
for (int j =1; j <=4; j ++)
System.out.println "\t"+i+"\t"+j+"\t"+(i*j));
13 }
How many times
does this execute?
The outer for contains a
compound statement
36
Loops: do-while
The do-while statement is useful when it is known the loop body
must execute at least once.
syntax :
do statement
while ( logical expression ) ;
37
Loops: do-while
38
Loops: do-while
The do-while statement is useful when it is known the loop body
must execute at least once.
syntax :
do statement
while ( logical expression ) ;
39
Loops: do-while
Example. Suppose we are adding the digits of a positive integer
There must be at least one digit to add to a total  can use do-while
System.out.println("Enter a number");
int n = kb.nextInt();
int sum = 0;
do {
sum += n % 10;
Executed at least once
n /= 10;
}
while (n>0);
System.out.println("sum is "+sum);
How many times does the loop execute if n is 5?
25?
0?
40
switch
a decision structure where one choice, of possibly many, different
choices are made
According to the value of
the expression a case is
executed
Execution of statements
follows unless a break
statement is encountered
41
Example 1
translating a letter grade to a numeric grade
42
Example 1
String grade;
double nGrade;
System.out.println("Enter letter grade:");
Scanner kb = new Scanner(System.in);
expression
grade = kb.next();
switch (grade) {
case "A": nGrade = 4.0;
break
break;
case "B": nGrade = 3.0;
break;
case "C": nGrade = 2.0;
break;
case "D": nGrade = 1.0;
If expression != any of
break;
the above cases values
default: nGrade = 0.0;
}
System.out.println(grade+" --> "+nGrade);
43
Conditional operator ? :
(not in text)
A decision structure that can replace an if-then-else
if ( a > b ) larger = a
else larger = b;
Can be written using ?: as
larger = ( a > b ) ? a : b;
General recommendation: use it when it makes your code clearer.
You will see ?: used frequently.
44
Conditional operator ? :
(not in text)
A decision structure that can replace an if-then-else
if ( a > b ) System.out.println(a);
else System.out.println(b);
Can be written using ?: as
System.out.println(( a > b ) ? a : b);
You can use ?: anywhere an expression could appear.
45
Conditional operator ? :
General recommendation: use it when it makes your code clearer.
Maybe these are not so clear:
for (int i=0; i<line.length(); i++){
char c = line.charAt(i);
encrypted+= (c=='a')?'e':((c=='e')?'a':c);
}
Or
encrypted+= c=='a'?'e':c=='e'?'a':c;
46