+ All Categories
Home > Documents > CSI 1301 ALGORITHMS - PART 2 CONDITIONAL BRANCH CONTROL STRUCTURE.

CSI 1301 ALGORITHMS - PART 2 CONDITIONAL BRANCH CONTROL STRUCTURE.

Date post: 14-Dec-2015
Category:
Upload: darrion-boughton
View: 220 times
Download: 2 times
Share this document with a friend
Popular Tags:
47
CSI 1301 ALGORITHMS - PART 2 CONDITIONAL BRANCH CONTROL STRUCTURE
Transcript

CSI 1301

ALGORITHMS - PART 2 CONDITIONAL BRANCH

CONTROL STRUCTURE

Conditional Branch

So far, in the method part of our algorithms, the instructions have been executed sequentially

However, sometimes we need to vary the order of execution of the instructions. The order will be determined by the value of a condition

We will test to determine whether the condition is true or false– If the condition is true, we will execute certain

instructions– If the condition is false, we will execute other

instructions

Definition of a Block

But first, let us define a block as group of related instructions– A block can contain one or as many instructions as we

want

BLOCK 1--------------------Get XGet YLet Z = X + YGive Z

BLOCK 2

----------------------

Let X = A + B * C /D

Block

The key feature of a block is that it has only one entrance (one way to come in)– By executing the first instruction in the block

and only one exit (one way out)– By executing the last instruction in the block

You cannot execute any other instruction in the block without starting with the first and ending with the last instructions

Simple Sequence of Blocks

Input Block--------------------Get XGet Y

Process Block------------------Let X = X + YLet Y = 2 * YLet Z = X + Y

Output Block-----------------Give Z

Test Blocks

By adding a test at the beginning of a block, we let the results of the test determine which block of instructions will be executed

TEST

True Block

----------------------

Do these Instructions if Test is True

False Block-----------------------Do these Instructions if the Test is False

What is a Test?

The test used in a conditional branching control structure contains a variable or expression that evaluates to either True or False

Logical Operators in a Test Expression

= Equal To

< Less Than

> Greater Than

<= Less Than or Equal To

>= Greater Than or Equal To

<> Not Equal To (Greater Than or Less Than)

Examples of Tests

TEST LOGICAL VALUE(3 + 2) = (7 – 2) True

5 <> (8 – 3) False((7*2)-3) < 12 True((9/3)*2)<=6 True(25-(3*5))>10 False23>= (12*2) False

Logical Tests

In practice, tests contain variables and expressions, not numbers

Suppose that X, Y and Z are 3, 5, 8 respectively

Test Logical Value

(X + Y) = (Z – 1) False

X = 3 True

(X > Y) False

Test Block

Indentation is used to show different blocks in an algorithm

To write a test block, use an IF statement, and indent the instructions to be executedIf (Test)

Do this statement

Do this statement as well

Do this statement after the If statement

Syntaxif (Test) Block1

Interpretation If Test is evaluated to true Block1 is executed, else Block2 is executed. The else is optionnal. Note that the indentation is important. It determines the beginning and the end of each block.

Test Block (syntax and interpretation)

if (Test) Block1else Block2

Algorithm 2.1

Write an algorithm to compute the absolute value of a number.– Name: ABSOLUTE– Givens: Number

• Change: None– Results: Value– Intermediates: None– Definition: Value := ABSOLUTE (Number)– -----------------------– Method

• Get Number

• If (Number >= 0) Let Value = Number

• If (Number < 0) Let Value = (-1) * Number

• Give Value

Else

It is redundant to do the test twice as inIF (X > 0)

Do this

IF (X <= 0) Do that

The test should be written asIf (X > 0)

Do this

Else (or Otherwise)Do that

Algorithm 2.1 (b)

Write an algorithm to compute the absolute value of a number using only one test

– Name: ABSOLUTE– Givens: Number

• Change:None– Results: Value– Intermediates: None– Definition: Value := ABSOLUTE (Number)– -----------------------– Method

• Get Number

If (Number >= 0) Let Value = Number

ElseLet Value = (-1) * Number

• Give Value

Algorithm 2.2

Write an algorithm which finds the largest of three given numbers

General Concept– Keep track of “Biggest so Far”

• Look at the first two numbers

• Store the larger of the two numbers in “Biggest so Far”

• Compare “Biggest so Far” with the third number

• If the third number is larger, then store it in “Biggest so Far”

Algorithm 2.2 Write an algorithm which

finds the largest of three given numbers

Name: BIG3Givens: N1, N2, N3

Change:NoneResults:LargestIntermediates: NoneDefinition: Largest := BIG3(N1,N2,N3)

Method------------------Get N1Get N2Get N3

If (N1 > N2)Let Largest = N1

Else Let Largest = N2

If (N3 > Largest)Let Largest = N3

Give Largest

Trace 2.1

(1) Get N1(2) Get N2(3) Get N3

(4) If (N1 > N2)(5) Let Largest = N1(6) Else (7) Let Largest = N2

(8) If (N3 > Largest)(9) Let Largest = N3

(10) Give Largest

LN N1 N2 N3 Largest Test 1 8 2 12 3 7 4 (8>12) 7 12 8 (7>12)10 Output 12

Trace Algorithm 2.2 with the values 8, 12, 7

Algorithm 2.3Write an algorithm which, when given an ordered

list X1, X2, & X3, modifies the list so that the values are in ascending order

General Concept• Look at the first two numbers, X1 and X2. If X1 is larger

than X2, swap them (remember the swap algorithm?)

• Look at X2 and X3. If X2 is larger than X3, swap them– This will put the largest number in the X3 position

– X2 may have changed, so we have to look at X1 again

• Look again at X1 and X2. If X1 is larger than X2, swap them– Now the list is in non-decreasing order

Algorithm 2.3

– Name: SORT3– Givens: X1,X2,X3

• Change: X1,X2,X3– Results: None– Intermediates: Temp– Definition:

SORT3(X1,X2,X3)

– Method– ----------------

• Get X1, X2, X3

• If (X1 > X2)Let Temp = X1

Let X1 = X2

Let X2 = Temp• If (X2 > X3)

Let Temp = X2

Let X2 = X3

Let X3 = Temp• If (X1 > X2)

Let Temp = X1

Let X1 = X2

Let X2 = Temp

• Give X1, X2, X3

Write an algorithm which, given an ordered list X1, X2 & X3, modifies it so that the values are in ascending order

Trace 2.2

Trace algorithm 2.3 with list X having values 3, 8 and 2 respectively

(1) Get X

(2) If (X1 > X2) (3) Let Temp = X1

(4) Let X1 = X2

(5) Let X2 = Temp (6) If (X2 > X3) (7) Let Temp = X2

(8) Let X2 = X3

(9) Let X3 = Temp(10) If (X1 > X2)(11) Let Temp = X1

(12) Let X1 = X2

(13) Let X2 = Temp

(14) Give X

LN X TEMP TEST

1 (3,8,2)

2 (3 > 8)

6 (8 > 2)

7 8

8 (3,2,2)

9 (3,2,8)

10 (3 > 2)

11 3

12 (2,2,8)

13 (2,3,8)

14 Output (2,3,8)

Multiple TestsSometimes we need to perform multiple related

tests – For example, in assigning grades, a student can receive

A+, A, A-….E, FWe can add an ELSE IF clause for multiple test

resultsIF (Test 1)

Execute block for Test 1Else IF (Test 2)

Execute block for Test 2Else

Execute block for Else

Algorithm 2.4

Write an algorithm which calculates the amount of money to charge for a ticket. The amount varies with the age of the individual. The charge for a person less than 16 is $7. The charge for a person over age 65 is $5 The charge is $10 for everyone else

Name: FAREGivens: Age

Change: NoneResults: PriceIntermediates: NoneDefinition: Price := FARE(Age)

Method---------------------Get Age

If (Age < 16)Let Price = $7

Else If (Age > 65)Let Price = $5

ElseLet Price = $10

Give Price

Trace 2.3

Trace algorithm 2.4 with the given age 35

(1) Get Age

(2) If (Age < 16)(3) Let Price = $7(4) Else If (Age > 65)(5) Let Price = $5(6) Else(7) Let Price = $10

(8) Give Price

LN Age Price Test

1 35

2 (35<16)

4 (35>65)

7 $10

8 Output $10

Algorithm 2.5

Given an employee’s eligible medical expenses for a calendar year, write an algorithm which computes the amount of reimbursement from group medical insurance. The insurance does not cover the first $100 of medical expenses. It pays 90% of the remaining amount in the first $2000 of expenses and 100% of any additional expenses.

Algorithm 2.5

Name: MEDICALGivens: Expense

Change: NoneResults: RefundIntermediates:

LL (Constant 100)UL (Constant 2000)

Definition: Refund := MEDICAL(Expense)

Method---------------------Set LL = 100Set UL = 2,000

Get Expense

If (Expense < LL)Let Refund = 0

Else If (Expense < UL)Let Refund = 90% (Expense-LL)

ElseLet Refund = 90% (UL-LL) +

100% (Expense - UL)

Give Refund

Trace 2.4

( 1) Set LL = 100( 2) Set UL = 2,000

( 3) Get Expense

( 4) If (Expense < 100)( 5) Let Refund = 0( 6) Else If (Expense < 2,000)( 7) Let Refund = 90% (Expense-100)( 8) Else( 9) Let Refund = 90% (1,900) + 100% (Expense - 2,000)

(10) Give Refund

LN UL LL Exp Refund Test

1,2 100 2K

3 3000

4 (3K<100)

6 (3K<2K)

9 2,710

10 Output 2,710

Trace Algorithm 2.5 for $3,000 worth of expenses

Additional Material

Flow Charts

Flow Charts

Logic is implemented with a Diamond Symbol

There are two exits, which should be labeled Y/N or T/F

The two paths need to join before the end of the flowchart

Algorithm 2.1(a)

Name: ABSOLUTEGivens: Number

Change: NoneResults: ValueIntermediates: NoneDefinition: Value :=

ABSOLUTE (Number)

StartABSOLUTE

Get Number

If (Number >= 0)

Let Value = Number

If (Number < 0)

Let Value = (-1) * Number

Give Value

FinishABSOLUTE

N

Y

N

Y

Algorithm 2.1(b)

Name: ABSOLUTEGivens: Number

Change: NoneResults: ValueIntermediates: NoneDefinition: Value :=

ABSOLUTE (Number)

StartABSOLUTE

Get Number

If (Number >= 0)

Let Value = Number Let Value = (-1) * Number

Give Value

FinishABSOLUTE

N

Y

Algorithm 2.2

Name: BIG3

Givens: N1, N2, N3

Change:None

Results:Largest

Intermediates: None

Definition:

Largest := BIG3(N1,N2,N3)

StartBIG3

Get N1Get N2Get N3

If (N1 > N2)

Let Largest = N1 Let Largest = N2

If (N3 > Largest)

Let Largest = N3

Give Largest

FinishBIG3

N

Y

N

Y

Algorithm 2.3

Name: SORT3Givens: X1,X2,X3

Change: X1,X2,X3Results: NoneIntermediates: TempDefinition: SORT3(X1,X2,X3)

StartSORT3

Get X1Get X2Get X3

If (X1 > X2)

Let Temp = X1Let X1 = X2

Let X2 = Temp

Give X1Give X2Give X3

FinishSORT3

N

Y

If (X2 > X3)

Let Temp = X2Let X2 = X3

Let X3 = Temp

N

If (X1 > X2)

Let Temp = X1Let X1 = X2

Let X2 = Temp

N

Y

Y

Algorithm 2.4

Name: FARE

Givens: Age

Change: None

Results: Price

Intermediates: None

Definition: Price := FARE(Age)

StartFARE

Get Age

If (Age < 16) If (Age > 65)

Let Price = $7 Let Price = 5$ Let Price = $10

Give Price

FinishFARE

N N

Y Y

Algorithm 2.5

Name: MEDICAL

Givens: Expense

Change: None

Results: Refund

Intermediates:

LL (Constant 100)

UL (Constant 2,000)

Definition:

Refund := MEDICAL(Expense)

StartMEDICAL

Get Expense

If (Expense < LL ) If (Expense < UL )

Let Refund = 0Let Refund =

90%(Expense – LL )Let Refund = 90%(UL-LL )+

100%(Expense – UL )

Give Refund

FinishMEDICAL

N N

Y Y

Set LL = 100Set UL = 2,000

NSD

NSD

Tricky to do in ExcelUse 2 columns

– Merge the 2 cells to form question

– Format Cells/Borders Diagonal lines can be put in

– Add Y/N cells

Algorithm 2.1(a)

Name: ABSOLUTEGivens: Number

Change: NoneResults: ValueIntermediates: NoneDefinition: Value :=

ABSOLUTE (Number)

Get Number

Y NLet Value = Number Do Nothing

Y NLet Value = (-1) * Number Do NothingGive Value

If (Number >=0)

If (Number < 0)

Algorithm 2.1(b)

Name: ABSOLUTEGivens: Number

Change: NoneResults: ValueIntermediates: NoneDefinition: Value :=

ABSOLUTE (Number)

Get Number

Y NLet Value = Number Let Value = (-1) * NumberGive Value

If (Number >=0)

Algorithm 2.2

Name: BIG3

Givens: N1, N2, N3

Change:None

Results:Largest

Intermediates: None

Definition:

Largest := BIG3(N1,N2,N3)

Get N1Get N2Get N3

Y NLet Largest = N1 Let Largest = N2

Y NLet Largest = N3 Do NothingGive Largest

If (N1 > N2)

If (N3 > Largest)

Algorithm 2.3

Name: SORT3Givens: X1,X2,X3

Change: X1,X2,X3Results: NoneIntermediates: TempDefinition: SORT3(X1,X2,X3)

Y NLet Temp = X1Let X1 = X2Let X2 = Temp

Y NLet Temp = X2Let X2 = X3Let X3 = Temp

Y NLet Temp = X1Let X1 = X2Let X2 = Temp

Give X2Give X3

Get X1Get X2Get X3

Give X1

If (X1 > X2)

Do Nothing

Do Nothing

Do Nothing

If (X1 > X2)

If (X2 > X3)

Algorithm 2.4

Name: FARE

Givens: Age

Change: None

Results: Price

Intermediates: None

Definition: Price := FARE(Age)

Y

Y NLet Price = $5 Let Price = $10

Get Age

Give Price

Let Price = $7

N

If (Age < 16)

If (Age > 65)

Algorithm 2.5

Name: MEDICALGivens: Expense

Change: NoneResults: RefundIntermediates: Definition: Refund := MEDICAL(Expense)

Y

Y NLet Refund = 90%(Expense - LL) Let Refund = 90%(UL-LL) + 100%(Expense - UL)

Let Refund = 0

If (Expense < UL)

Give Refund

Set LL= 100Set UL = 2,000Get Expense

If (Expense < LL)

N

Homework

For each of the following questions:Develop an algorithm

Trace the algorithm with suitable data

•Write an algorithm to reverse the digits in a three digit number and then add that number to 500. For example, 468 becomes 864. When added to 500, the result is 1364.

•Write an algorithm to get the names and ages of two people. Return the name of the person who is older (in the format “x is older than y”, where x and y are the names of the two people), unless the two people are the same age, in which case, return the message “x is the same age as y”.

An automotive sales representative’s commission is calculated as a percentage of the sale: – 8% of the first $5,000.00 of the sale price– 10% on the remainder of the sale price, if the remainder

is less than or equal to $80,000.00 or– 12.5% on the remainder, if the remainder is more than

$80,000.00Develop an algorithm that will accept the sale

price of the automobile and calculate and display the sales representative’s commission.


Recommended