Topic4 - Problem Solving With Selection Control
Topic4 - Problem Solving With Selection Control
Selection Structure
Boolean Data Type and Comparison Operators
If Statement and Two-Way Selection Statements
Nested and Multi-Way Selection Statements
1
Learning Outcomes
• At the end of this chapter, student should be
able to:
– Analyse and solve programming problem (C4, CTPS)
– Use problem-solving chart to develop a solution using
one-way and nested selection statement (C3,CTPS)
– Construct program using one-way and nested selection
statement (C3)
– Use one –way and nested selection statement to develop
problem solution (C3)
– Develop problem and construct program using the case
logic structure. (C3)
2
Sequential Structure
From previous problems (Topic 3),
•Performs a series of steps in a sequence.
•Order – important to get the accurate output.
• Syntax:
start
Instruction
Instruction
end
3
Algorithm, Flowchart, and Pseudocode
to Enter and Print Two Variables
0-4
Flowchart Diagram of the Selection
Structure
Selection/decision Structure
•Make decision based on certain conditions
0-5
The boolean Type and Operators
If you need to compare two values, such as whether i is
greater than j, Java provides six comparison operators
(also known as relational operators – Topic 2) that can be
used to compare two values.
6
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
7
Logical Operators
Operator Name
! not
&& and
|| or
8
Selection Statements
• if Statements
• switch Statements
• Conditional Operators
9
If statements
• Implemented using the IF/THEN/ELSE instruction.
• Tells the computer that
– IF a condition is true,
– THEN execute a set of instructions,
– or ELSE execute another set of instructions
• ELSE part is optional, as there is not always a set of
instructions if the conditions are false.
• Format:
IF <condition(s)> THEN
<TRUE instruction(s)>
ELSE
<FALSE instruction(s)>
10
One-Way selection Statements
• Problem 1
• Calculate the area of a circle if the radius
is positive where
area = pi * radius * radius
11
Problem 1
• PAC
Given Data Required results
radius area
Processing Required Solution Aternatives
if (radius is positive) pi as a constant (pi= 3.14)
Calculate area
Print area
• IPO
Input Processing Module Output
radius Enter radius area
If (radius > 0) then
area = radius x radius x 3.14
Print area
12
• Flowchart
Problem 1
• Pseudocode
Start
Start
Read radius Read radius
if radius >0 then
false area= radius * radius * 3.14
print area
If (radius>= 0)
endif
End
true
Print area
End
13
Problem 1 (Code segment)
if (booleanExpression) {
statement(s);
}
if (radius >= 0) {
area = radius * radius * 3.14;
System.out.println("The area“ + “ for the circle of radius “ + radius +
“ is " + area);
}
14
Note
• Braces can be omitted if the block contains a single
statement
if (i > 0) {
System.out.println("i is a positive integer");
}
…is equivalent to
if (i > 0)
System.out.println("i is a positive integer");
15
Note
Outer parentheses required
16
Two-Way Selection Statements
17
Problem 1
• PAC
Given Data Required results
radius area
Processing Required Solution Aternatives
if (radius is positive) pi as a constant (pi= 3.14)
Calculate area
Print area
Otherwise
Print “Radius must positive”
• IPO
Input Processing Module Output
radius Enter radius area or
If (radius > 0) then “Radius
area = radius x radius x 3.14 must
Print area positive”
Else
Print ”Radius must positive”
Endif 18
• Flowchart
Problem 1
• Pseudocode
Start
Start
Read radius Read radius
if radius >0 then
false area= radius * radius *
If (radius>= 0) 3.14
print area
Print “Radius must
true positive” Else
area = radius * radius * 3.142 pritnt “Radius must
positive”
Print area endif
End
End
19
Problem 1 (Code segment)
if (radius > 0) {
area = radius * radius * 3.14;
System.out.println("The area“ + “ for the circle of radius “ + radius +
“ is " + area);
else
System.out.println(”Radius must positive”);
}
20
Example
• Assume your are calculating pay at an hourly
rate, and overtime pay (over 40 hours) at 1.5
times the hourly rate.
– IF the hours are greater than 40, THEN the pay is
calculated for overtime, or ELSE the pay is calculated
in the usual way.
21
Example—Two Possible Actions or
Sets of Actions
0-22
import java.util.Scanner;
class PayCalculation {
public static void main(String[] args) {
double hours, payRate, pay;
24
Caution
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0); { Wrong
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation
error or a runtime error, it is a logic error.
This error often occurs when you use the next-line block
style.
25
Nested and Multi-way Selection
Statements
• Multiple decisions.
• Use to solve the problems that require the
implementation of more than two alternatives
26
Ex1-Nested If/Then/Else
Instructions
0-27
Nested if/then/else Instructions
if (marks >= 80){
grade = ‘A’;
if (marks == 100)
System.out.println(“Full marks!”);
}
28
Nested if/then/else Instructions
if (marks >= 80)
if (marks == 100)
System.out.println(“Full marks!”);
equivalent to
29
Multiple Alternative if
Statements
if (score >= 90.0) if (score >= 90.0)
grade = 'A'; grade = 'A';
else else if (score >= 80.0)
if (score >= 80.0) Equivalent grade = 'B';
grade = 'B'; else if (score >= 70.0)
else grade = 'C';
if (score >= 70.0) else if (score >= 60.0)
grade = 'C'; grade = 'D';
else else
if (score >= 60.0) grade = 'F';
grade = 'D';
else
grade = 'F';
This is better
30
Multi-Way if-else Statements
false
score >= 90
false
true score >= 80
false
grade = 'A' true score >= 70
false
grade = 'B' rue score >= 60
grade = 'D'
grade = 'F'
31
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
32
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
33
animation
Trace if-else statement
Suppose score is 70.0 The condition is true
34
animation
Trace if-else statement
Suppose score is 70.0 grade is C
35
animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement
36
Note
The else clause matches the most recent if clause
in the same block.
int i = 1; int i = 1;
int j = 2; int j = 2;
int k = 3; int k = 3;
Equivalent
if (i > j) if (i > j)
if (i > k) if (i > k)
System.out.println("A"); System.out.println("A");
else else
System.out.println("B"); System.out.println("B");
(a) (b)
37
Note, cont.
Nothing is printed from the preceding statement. To
force the else clause to match the first if clause, you
must add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
38
Exercise
A vendor company will give some discounts on its products based on
the total units bought by the customer and the price of each unit. The
table shows the discount given with the price and the total units. Write
if…else statements based on the table.
39
Exercise
Divide and conquer strategy...
40
Exercise
A retailer will give discount based on the quantity of the item that
customer will buy. The customer will get 10% discount if buy 2 items,
20% discount for 4 items and 50% if more than 5 items. Solve this
problem by display the discount that customer will get.
41
Exercise
Code Specialization
480 Multimedia
481 Computer System
482 Software Engineering
483 Computer Network
42
C
43
Case Logic Structure
44
Case Logic Structure
45
Example
Example:
Grade Point
A 4.0
B 3.0
C 2.0
Case of Grade
D 1.0
F 0.0
point = 4.0 point = 3.0 point = 2.0 point = 1.0 point = 0.0
46
switch Statement Rules
The switch-expression must
yield a value of char, byte,
short, or int type and must switch (switch-expression) {
always be enclosed in case value1:
parentheses. statement(s)1;
break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression. case valueN: statement(s)N;
The resulting statements in the break;
case statement are executed when default: statement(s)-for-
the value in the case statement default;
matches the value of the switch- }
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x. 47
switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the end case value1: statement(s)1;
of each case in order to terminate
the remainder of the switch break;
statement. If the break statement case value2: statement(s)2;
is not present, the next case break;
statement will be executed.
…
case valueN: statement(s)N;
break;
The default case, which is
default: statement(s)-for-
optional, can be used to
default;
perform actions when none of
the specified cases matches }
the switch-expression.
The case statements are executed in sequential order,
but the order of the cases (including the default case)
does not matter. However, it is good programming style
to follow the logical sequence of the cases and place
the default case at the end. 48
Example
Grade Point switch(grade){
A 4.0 case ‘A’: point = 4.0;
B 3.0 break;
C 2.0 case ‘B’: point = 3.0;
D 1.0
break;
F 0.0
case ‘C’: point = 2.0;
break;
case ‘D’: point = 1.0;
break;
case ‘F’: point = 0.0;
break;
}
49
import java.io.IOException;
import java.util.Scanner;
public class Grade_Point{
Example
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter grade: ");
char grade = (char) System.in.read();
double point;
switch (grade) {
case 'A' : point = 4.0;
break;
case 'B' : point = 3.0;
break;
case 'C' : point = 2.0; What happen if the
break;
case 'D' : point = 1.0; user entered ‘a’
break;
case ‘F' : point = 0.0;
instead of ‘A’?
break;
default : System.out.println(“Grade unknown");
}
System.out.print("Point : " + point);
}
}
50
We can include both uppercase
Example
and lowercase letters in the case.
Equivalent to
if (grade==‘A’) || (grade==‘a’)
switch(grade){
case ‘A’: case ‘a’: point = 4.0;
break;
case ‘B’: case ‘b’: point = 3.0;
break;
case ‘C’: case ‘c’: point = 2.0;
break;
case ‘D’: case ‘d’: point = 1.0;
break;
default : point = 0.0;
break;
}
51
Exercise
Code Specialization
480 Multimedia
481 Computer System
482 Software Engineering
483 Computer Network
52
animation
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
53
animation
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
54
animation
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
55
animation
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
56
animation
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
57
animation
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
Next statement;
58
animation
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
59
animation
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
60
animation
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
61
animation
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
62
animation
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
Next statement;
63
Example: Medical Plans
A company has four different medical plans. The
programmer has given each plan a code corresponding to
the beginning initial of the company: Plan 1 = F, Plan 2 = B,
Plan 3 = K, Plan 4 = E.
The company pays for all of Plan 1. The individual has to
pay for part of the others. The payroll deduction for Plan 2
= 4.65, for Plan 3 = 7.85, and for Plan 4 = 5.50. Any other
codes are considered in error.
Write the algorithm and draw the flowchart for a module
to determine the payroll deduction.
64
Example: Medical Plans
65
Example: Computing Taxes
The US federal personal income tax is calculated based on
the filing status and taxable income. There are four filing
statuses: single filers, married filing jointly, married filing
separately, and head of household. The tax rates for 2002
are shown in the table below.
66
Example: Computing Taxes, cont.
if (status == 0) {
// Compute tax for single filers
}
else if (status == 1) {
// Compute tax for married file jointly
}
else if (status == 2) {
// Compute tax for married file separately
}
else if (status == 3) {
// Compute tax for head of household
}
else {
// Display wrong status
}
67
switch Statements
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(0);
}
68