Top Banner
1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm
57

1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

Jan 13, 2016

Download

Documents

Carol Copeland
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

1

CSE1301Computer Programming

Lecture 3:Components of an Algorithm

Page 2: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

2

Recall

• What is the problem solving process?

• What is an algorithm?

• What are some examples?

• What are values and variables?

• What are instructions or primitives?

Page 3: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

3

Topics

• More components of an algorithm

• The software development process

• Top-down design

Page 4: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

4

Components of an AlgorithmValues and Variables

• Instruction (a.k.a. primitive)– Sequence (of instructions)– Procedure (involving instructions) – Selection (between instructions)– Repetition (of instructions)

• Documentation (beside instructions)

Page 5: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

5

Family Tree of

Programming

Languages

The components of Algorithms

That we use correspond

To “structured programming”

(Algol, Pascal, C, Modula, Ada…)

Page 6: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

6

Variables

This jarcan contain

10 cookies

50 grams of sugar

3 slices of cake

etc.

ValuesVariable

• Are containers for values – places to store values

• Example:

Page 7: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

7

Restrictions on Variables

• Variables may be restricted to contain a specific type of value

Page 8: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

8

Components of an AlgorithmValues and VariablesInstruction (a.k.a. primitives)

• Sequence (of instructions)

• Procedure (involving instructions)

• Selection (between instructions)

• Repetition (of instructions)

• Documentation (beside instructions)

Page 9: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

9

Instructions (Primitives)

• Some action that is – simple– unambiguous– that the system knows about...– ...and should be able to actually do

Page 10: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

10

Instructions – Examples

• Take off your shoes

• Count to 10

• Cut along dotted line

• Knit 1

• Purl 2

• Pull rip-cord firmly

• Sift 10 grams of arsenic

Directions to perform specific actions on values and variables.

Page 11: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

11

Instructions -- Application

• Some instructions can only be applied to a specific type of values or variables

• Examples:

Page 12: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

12

Instructions (Primitives) -- Recommendations

• When writing an algorithm, make each instruction simple and unambiguous

• Example:

Cut chicken into pieces and brown the pieces on all sides in a casserole dish in hot olive oil.

Cut chicken into pieces.

Heat olive oil in a casserole dish.

Brown the chicken pieces in the casserole dish.

Page 13: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

13

Instruction (Primitives)• When writing an algorithm, make the

instructions simple and unambiguous.

• Example:

Cut chicken into pieces and brown the pieces on all sides in a casserole dish in hot olive oil.

Cut chicken into pieces.

Heat olive oil in a casserole dish.

Brown the chicken pieces in the casserole dish.

A “sequence” of simple instructions

Page 14: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

14

Sequence

• A series of instructions

• ...to be carried out one after the other...

• ...without hesitation or question

• Example:

– How to cook a Gourmet MealTM

Page 15: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

15

Sequence -- Example

1. Open freezer door 2. Take out Gourmet Meal™ 3. Close freezer door 4. Open microwave door 5. Put Gourmet Meal™ on carousel 6. Shut microwave door 7. Set microwave on high for 5 minutes 8. Start microwave 9. Wait 5 minutes 10. Open microwave door 11. Remove Gourmet Meal™ 12. Close microwave door

Page 16: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

16

Components of an Algorithm

Values and VariablesInstruction (a.k.a. primitives)Sequence (of instructions)

• Procedure (involving instructions)

• Selection (between instructions)

• Repetition (of instructions)

• Documentation (beside instructions)

Page 17: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

17

Procedure

• A named sequence of instructions

• So that you can– Refer to it collectively (by name)– ...instead of individually (by each instruction in

the sequence)

• Example:

– Drive_To_Uni

Page 18: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

18

Procedure -- Example procedure Drive_To_Uni { 1. find car keys 2. disable car alarm 3. open car door 4. get in car 5. shut car door 6. put keys in ignition 7. start car 8. back car out of

driveway 9. drive to end of street 10. turn right 11. drive to end of street 12. turn left ...etc...etc...etc

...etc...etc...etc...

52. find parking space

53. pull into parking space

54. turn off engine

55. remove keys from ignition

56. open car door

57. get out

58. shut car door

59. lock car door

60. enable alarm

}

Page 19: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

19

Procedure – Example (cont)

procedure Do_Wednesday{ Wake_up Have_Shower Eat_Breakfast Drive_To_Uni Sit_1301_Lecture ...etc...etc...etc... Drive_From_Uni ...etc...etc...etc...}

procedure Do_Week

{

Do_Monday

Do_Tuesday

Do_Wednesday

Do_Thursday

...etc...etc...etc...

}

Page 20: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

20

Procedure – Example (cont)

procedure Do_Wednesday{ Wake_up Have_Shower Eat_Breakfast Drive_To_Uni Sit_1301_Lecture ...etc...etc...etc... Drive_From_Uni ...etc...etc...etc...}

In this subject, we also use the following words to refer to a “Procedure” :

• Sub-routine• Module• Function

Page 21: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

21

Procedure – Example (cont)

procedure Do_Wednesday{ Wake_up Have_Shower Eat_Breakfast Drive_To_Uni Sit_1301_Lecture ...etc...etc...etc... Drive_From_Uni ...etc...etc...etc...}

We use brackets to mark the beginning and end of a sequence.

Page 22: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

22

Procedure – Example (cont)

procedure Do_Wednesday{ Wake_up Have_Shower Eat_Breakfast Drive_To_Uni Sit_1301_Lecture ...etc...etc...etc... Drive_From_Uni ...etc...etc...etc...}

An instruction invoking a procedure is known as a “procedure call”

Page 23: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

23

Procedure• A procedure may have a set of parameters

procedure customerService ( myName ,timeOfDay ){ say “Good timeOfDay” say “My name is myName” say “How can I help you?”}

customerService ( “Ann”, “Morning” )

customerService (“Ann”, “Afternoon” )

customerService ( “Jeff”, “Afternoon” )

Page 24: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

24

Components of an Algorithm

Values and VariablesInstruction (a.k.a. primitives)Sequence (of instructions)Procedure (involving instructions)

• Selection (between instructions)

• Repetition (of instructions)

• Documentation (beside instructions)

Page 25: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

25

Selection• An instruction that decides which of two

possible sequences is executed

• The decision is based on a single true/false condition

• Examples:

– Car repair

– Reciprocals

Page 26: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

26

Selection Example -- Car Repairif (motor turns) then {

CheckFuelCheckSparkPlugsCheckCarburettor

}else {

CheckDistributorCheckIgnitionCoil

}

Page 27: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

27

Selection Example –Car Repair (cont)

if (motor turns) then {

CheckFuelCheckSparkPlugsCheckCarburettor

}else {

CheckDistributorCheckIgnitionCoil

}

Should be a true or false condition.

Page 28: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

28

Selection Example --Car Repair (cont)

if (motor turns) then {

CheckFuelCheckSparkPlugsCheckCarburettor

}else {

CheckDistributorCheckIgnitionCoil

}

Sequence if the condition is true.

Page 29: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

29

Selection Example --Car Repair (cont)

if (motor turns) then {

CheckFuelCheckSparkPlugsCheckCarburettor

}else {

CheckDistributorCheckIgnitionCoil

}

Sequence if the condition is false.

Page 30: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

30

Selection Example -- Reciprocals

Q. Give an algorithm for computing the reciprocal of a number.

Examples:

Reciprocal of 2: 1/2

Reciprocal of -3/4: 1/(-3/4) = -4/3

Reciprocal of 0: “undefined”

Page 31: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

31

Selection Example – Reciprocals (cont)

Q. Give an algorithm for computing the reciprocal of a number.

Algorithm: input Num if (Num is not equal 0) then { output 1/Num } else {

output "infinity" }

Page 32: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

32

Selection Example-- Reciprocals

input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity"

}

Algorithm:

Num is a variable whose value depends on the actual number the user provides.

Page 33: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

33

Selection Example – Reciprocals (cont)

input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity"

}

Algorithm:

Condition depends on the value of Num

Page 34: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

34

Selection Example – Reciprocals (cont)

input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity"

}

Algorithm:

For a given value of Num, only one of these two sequences can be executed

Page 35: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

35

Selection Example – Reciprocals (cont)

input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity"

}

Algorithm:

Executed if Num is not equal to 0

Page 36: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

36

Selection Example – Reciprocals (cont)

input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity"

}

Algorithm:

Executed if Num is equal to 0

Page 37: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

37

Selection -- Exercise

input Num if (Num is not equal 0) then { output 1/Num } else {

output "infinity" }

Will the following algorithms produce the same output?

Algorithm 1: input Num

if (Num is not equal 0)

then

{

output 1/Num

}

output "infinity"

Algorithm 2:

Page 38: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

38

Selection – Several Conditions

• What if several conditions need to be satisfied?if ( today is Wednesday and the time is 10.00am )

then

{

Go to CSE1301 Lecture

}

else

{

Go to Library

} Solution 1

Page 39: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

39

Selection – Several Conditions (cont)

Solution 2

Often called a “nested selection”

if ( today is Wednesday ) then {

if ( the time is 10.00am ) then { Go to CSE1301 Lecture } } else ...etc...etc...etc...

Page 40: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

40

Selection – At Least One of Several Conditions

• What if at least one of several conditions needs to be satisfied?if ( I feel hungry or the time is 1.00pm or my

mate has his eye on my lunch )

then

{

Eat my lunch now

}

Page 41: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

41

Components of an AlgorithmValues and VariablesInstruction (a.k.a. primitives)Sequence (of instructions)Procedure (involving instructions) Selection (between instructions)

• Repetition (of instructions)

• Documentation (beside instructions)

Page 42: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

42

Repetition

• Repeat an instruction...– ...while (or maybe until) some true or

false condition occurs– Test the condition each time before

repeating the instruction• Also known as iteration or loop• Example:

– Algorithm for getting a date

Page 43: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

43

Repetition -- Exampleprocedure AskOnDate ( name, time, location )

{

Phone(name)

Say("Hey", name, "it's your lucky day!")

Say("Wanna come to", location, "at", time, "?")

ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){ Say("Oh please!")

add 1 to begging count

ListenToReply ( )}

}

Page 44: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

44

Repetition – Example (cont)procedure AskOnDate ( name, time, location ){

Phone(name)Say("Hey", name, "it's your lucky day!")Say("Wanna come to", location, "at", time, "?")ListenToReply ( )start begging count at zerowhile ( reply is "No" and begging count < 100 ){ Say("Oh please!") add 1 to begging count ListenToReply ( )}

}

Condition is tested before sequence

Page 45: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

45

Repetition – Example (cont)

procedure AskOnDate ( name, time, location ){

Phone(name)Say("Hey", name, "it's your lucky day!")Say("Wanna come to", location, "at", time, "?")ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){ Say("Oh please!") add 1 to begging count ListenToReply ( )}

}

Sequence may not get executed at all

Page 46: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

46

Repetition – Example (cont)procedure AskOnDate ( name, time, location ){

Phone(name)Say("Hey", name, "it's your lucky day!")Say("Wanna come to", location, "at", time, "?")ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){ Say("Oh please!") add 1 to begging count ListenToReply ( )}

}

Ensure initial values of variables used in the conditions are set correctly

Page 47: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

47

Repetition – Example (cont)

procedure AskOnDate ( name, time, location ){

Phone(name)Say("Hey", name, "it's your lucky day!")Say("Wanna come to", location, "at", time, "?")ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){ Say("Oh please!") add 1 to begging count ListenToReply ( )}

}

Ensure the variables used in the conditions are updated in each iteration

Page 48: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

48

Repetition – Example (cont)

procedure AskOnDate ( name, time, location )

{

Phone(name)

Say("Hey", name, "it's your lucky day!")

Say("Wanna come to", location, "at", time, "?")

ListenToReply ( )start begging count at zerowhile (reply is "No" and begging count < 100){ Say("Oh please!")

}

}Infinite loop

• What if we don’t increment the begging count?

Page 49: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

49

Repetition – Variation

decide on Time and Location

initialise booking to “unsuccessful”

while ( not successfully booked )

{

get next Name in little black book

AskOnDate(Name, Time, Location)

DetermineBookingSuccess

}

SighWithRelief

Page 50: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

50

Components of an AlgorithmValues and VariablesInstruction (a.k.a. primitives)Sequence (of instructions)Procedure (involving instructions) Selection (between instructions)Repetition (of instructions)

• Documentation (beside instructions)

Page 51: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

51

Documentation

• Records what the algorithm does

• Describes how it does it

• Explains the purpose of each component of the algorithm

• Notes restrictions or expectations

• Example:– Getting a date (again)

Page 52: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

52

Documentation -- ExampleThink of something romantic to dodecide on time and location

Work through address book to look for a personinitialise booking to “unsuccessful”until (successfully booked){ get next Name in little black book AskOnDate(Name, Time, Location) DetermineBookingSuccess}

Assumes that I will find someone in the book before it runs outSighWithRelief

Page 53: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

53

Components of an Algorithm

Values and VariablesInstruction (a.k.a. primitives)Sequence (of instructions)Procedure (involving instructions) Selection (between instructions)Repetition (of instructions)Documentation (beside instructions)

Page 54: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

54

The Software Development Process

• Define the problem clearly

• Analyse the problem thoroughly

• Design an algorithm carefully

• Code the algorithm efficiently

• Test the code thoroughly

• Document the system lucidly

Page 55: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

55

Top-down Algorithm Design

• Write down what you have to do• Break that into 3-7 smaller steps• Break each step into 3-7 smaller steps• Keeping subdividing until each individual

step is easy enough to do – i.e., until it is a single instruction

• Example:– Learning

Page 56: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

56

Top-down Design -- Example

Learn

Prepare

Study

Reinforce

ReadMake notesPrepare questions

Attend lectureListen and thinkComplete pracAttend tute

Record answers to questions

Revise notes

Read lecture notesRead textbook

Read exerciseDesign algorithmCode solutionTest and document

Record insights

Page 57: 1 CSE1301 Computer Programming Lecture 3: Components of an Algorithm.

57

Reading

• Deitel & Deitel, C: How to program– Chapter 3, Sections 3.8 to 3.13