0% found this document useful (0 votes)
23 views

Programming Chap 4

Uploaded by

osesayjr
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Programming Chap 4

Uploaded by

osesayjr
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 36

DECISION STRUCTURES

•Introduction to Decision Structures


•Dual Alternative Decision Structures
•Comparing Strings
•Nested Decision Structures
•The Case Structure
•Logical Operators
Introduction to Decision Structures

A decision structure allows a program to perform actions


only under certain conditions. If the condition does not
exist, the action is not performed.
For example, consider a pay calculating program that
determines whether an employee has worked overtime. If
the employee has worked more than 40 hours, he or she
gets paid extra for all the hours over 40. Otherwise, the
overtime calculation should be skipped. Programs like this
require a different type of control structure: one that can
execute a set of statements only under certain
circumstances. This can be accomplished with a decision
structure.
(Decision structures are also known as selection
structures.)
Introduction to Decision Structures (Continue)
A simple decision structure for an everyday task

In the flowchart, the diamond symbol indicates some condition


that must be tested. In this case, we are determining whether
the condition Cold outside is true or false. If this condition is
true, the action Wear a coat is performed. If the condition is
false, the action is skipped. The action is conditionally executed
because it is performed only when a certain condition is true.
Combining Structures
You cannot use decision structures alone to create a
complete program. You use a decision structure to handle
any part of a program that needs to test a condition and
conditionally execute an action depending on the outcome
of the condition. For other parts of a program you need to
use other structures.

Combining sequence structures with a decision


structure (See flowchart below)
Go to the
window
Sequence structure
Read
thermometer

Cold True
Decision structure
outside
Wear a coat.
False

Open the door

Sequence structure
Go outside

End
The flowchart in the figure starts with a sequence
structure. Assuming you have an outdoor thermometer in
your window, the first step is Go to the window, and the
next step is Read thermometer. A decision structure
appears next, testing the condition Cold outside. If this is
true, the action Wear a coat is performed. Another
sequence structure appears next. The step Open the door
is performed, followed by Go outside.

NOTE: Quite often, structures must be nested inside of


other structures.
A sequence structure nested inside a decision
structure

Cold True
outside
Decision structure Wear a coat

Wear a hat Sequence structure


False

Wear gloves
Writing a Decision Structure in Pseudocode

If condition Then
statement
statement These statements are conditionally
executed.
etc.
End If
Boolean Expressions and Relational Operators
All programming languages allow you to create expressions
that can be evaluated as either true or false. These are called
Boolean expressions. Typically, the Boolean expression that is
tested by an If-Then statement is formed with a relational
operator.
A relational operator determines whether a specific
relationship exists between two values. For example, the
greater than operator (>) determines whether one value is
greater than another. The equal to operator (==) determines
whether values are equal.
Relational operators

Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
Boolean expressions using relational operators

Expression Meaning
x>y Greater than
x<y Less than
x >= y Greater than or equal to
x <= y Less than or equal to
x == y Equal to
x != y Not equal to
Boolean expressions using relational operators

Expression Meaning
x >y Greater than
x<y Less than
x >= y Greater than or equal to
x <= y Less than or equal to
x == y Equal to
x != y Not equal to
Example 1
If sales > 50000 Then
Set bonus = 500.0
Set commissionRate = 0.12
Display "You've met your sales quota!"
End If
Example 1 (Continue)

True
sales >
50000

Set bonus = 500.0

Set
False commissionRate =
0.15

Display “You’ve
met your sales
quota!”
Exercise
Alpha teaches a science class and her students are required to
take three tests. He wants to write a program that his students
can use to calculate their average test score.
He also wants the program to congratulate the student
enthusiastically if the average is greater than 95.

Algorithm:
1. Get the first test score.
2. Get the second test score.
3. Get the third test score.
4. Calculate the average.
5. Display the average.
6. If the average is greater than 95, congratulate the user.
Pseudocode:
Declare Real test1, test2, test3, average
// Get test score
Display “Enter the score for test #1.”
Input test1
Display “Enter the score for test #2.”
Input test2
Display “Enter the score for test #3.”
Input test3
Set average = (test1 + test2 + test3) / 3 // Calculate the
average
Display “The average is “, average // Display the average.
If average > 95 Then
Display "Congratulations! Great average!"
End If
Flowchart
A A
Start

Declare Real test1, Display “Enter the


Average True
test2, test3, average score for test #3.”
> 95

Display “Enter the


Input test3
score for test #1.”
Display
False “Congratulations!
Input test1 Great average!.”
Set average=(test1+test2+test3) / 3

Display “Enter the


score for test #2.”
Display “The End
average is ”, average
Input test2

A
A
Dual Alternative Decision Structures
A dual alternative decision structure will execute one group
of statements if its Boolean expression is true, or another
group if its Boolean expression is false.

True
False
Temperat
ure < 40

Display “Nice weather Display “A little cold,


we’re having” isn’t it?”
Pseudocode
We write a dual alternative decision structure as an If-Then-
Else statement. Here is the general format of the If-Then-
Else statement:
If condition Then
statement
statement These statements are executed if the condition is true
etc.
Else
statement
statement These statements are executed if the condition is false
etc.
End If
Comparing Strings
Most programming languages allow you to compare strings. This
allows you to create decision structures that test the value of a
string.
Example 1:
Declare String password // A variable to hold a password.
// Prompt the user to enter the password.
Display "Enter the password."
Input password
// Determine whether the correct password was entered.
If password == “prospero” Then
Display "Password accepted."
Else
Display "Sorry, that is not the correct password."
End If
Nested Decision Structures

To test more than one condition, a decision structure can


be nested inside another decision structure.

For example, consider a program that determines


whether a bank customer qualifies for a loan. To qualify,
two conditions must exist: (1) the customer must earn at
least $30,000 per year, and (2) the customer must have
been employed at his or her current job for at least two
years.
Assume that the salary variable contains the customer’s
annual salary, and the yearsOnJob variable contains the
number of years that the customer has worked on his or
her current job.
Declare Real salary, yearsOnJob
Display "Enter your annual salary."
Input salary
Display "Enter the number of years on your current job."
Input yearsOnJob
If salary >= 30000 Then
If yearsOnJob >= 2 Then
Display "You qualify for the loan."
Else
Display "You must have been on your current"
Display "job for at least two years to qualify."
End If
Else
Display "You must earn at least $30,000"
Display "per year to qualify."
End If
False salary >= True
30000

Display "You must False True


yearsOnJ
earn at least $30,000"
ob >= 2

Display "per year to Display "You must have Display "You qualify
qualify." been on your current" for the loan."

Display "job for at least


two years to qualify."

End
Testing a Series of Conditions with If-Then-Else If
Statement
Dr. Vandy teaches a programming class and uses the following
10 point grading scale for all of his exams:
Test Score Grade
90 and above A
80–89 B
70–79 C
60–69 D
Below 60 F
He has asked you to write a program that will allow a student
to enter a test score and then display the grade for that score.
Declare Real score
Display "Enter your test score."
Input score
If score < 60 Then
Display "Your grade is F."
Else If score < 70 Then
Display "Your grade is D."
Else If score < 80 Then
Display "Your grade is C."
Else If score < 90 Then
Display "Your grade is B."
Else
Display "Your grade is A."
End If
The Case Structures
The case structure is a multiple alternative decision structure.
It allows you to test the value of a variable or an expression
and then use that value to determine which statement or set
of statements to execute.

mon
th

1 2 3 Default
Display Display
"January" Display “March" Display “April"
“February"
Declare Integer month
Display “Enter the month"
Input month
Select month
Case 1:
Display “January"
Case 2:
Display “February"
Case 3:
Display “March”
Default:
Display “April”
End Select
Logical Operators
The logical AND operator and the logical OR operator allow you to
connect multiple Boolean expressions to create a compound
expression. The logical NOT operator reverses the truth of a
Boolean expression.
AND: The AND operator connects two Boolean expressions into
one compound expression. Both subexpressions must be true for
the compound expression to be true.
OR: The OR operator connects two Boolean expressions into one
compound expression. One or both subexpressions must be true
for the compound expression to be true. It is only necessary for
one of the subexpressions to be true, and it does not matter which.
NOT: The NOT operator is a unary operator, meaning it works with
only one operand. The operand must be a Boolean expression. The
NOT operator reverses the truth of its operand. If it is applied to an
expression that is true, the operator returns false. If it is applied to
an expression that is false, the operator returns true.
Compound Boolean expressions using logical
operators
Expression Meaning
x > y AND a < b Is x greater than y AND is a less than
b?
x == y OR x == z Is x equal to y OR is x equal to z?
NOT (x > y) Is the expression x > y NOT true?
The AND Operator

The AND operator takes two Boolean expressions as operands and


creates a compound Boolean expression that is true only when both
subexpressions are true. The following is an example of an If-Then
statement that uses the AND operator:

If temperature < 20 AND minutes > 12 Then


Display "The temperature is in the danger zone."
End If
The AND Operator (Continue)
Expression Value of the Expression
true AND false false
false AND true false
false AND false false
true AND true true
The OR Operator
The OR operator takes two Boolean expressions as operands and
creates a compound Boolean expression that is true when either of the
subexpressions is true. The following is an example of an If-Then
statement that uses the OR operator:

If temperature < 20 OR temperature > 100 Then


Display "The temperature is in the danger zone."
End If
The OR Operator (Continue)
Expression Value of the Expression
true AND false true
false AND true true
false AND false false
true AND true true
The NOT Operator
The NOT operator is a unary operator that takes a Boolean expression
as its operand and reverses its logical value. In other words, if the
expression is true, the NOT operator returns false, and if the
expression is false, the NOT operator returns true. The following is an
If-Then statement using the NOT operator:

If NOT(temperature > 100) Then


Display "This is below the maximum temperature."
End If
The NOT Operator (Continue)
Expression Value of the Expression
NOT true false
NOT false true
Exercise
A software company sells a package that retails for $99. Quantity
discounts are given according to the following table:

Quantity Discount
10 – 19 20%
20 – 49 30%
50 – 99 40%
100 or more 50%

Design a program that asks the user to enter the number of packages
purchased. The program should then display the amount of the
discount (if any) and the total amount of the purchase after the
discount.

You might also like