54
1 Components of an Algorithm Adhi Harmoko S,M.Komp

Components of an Algorithm - Universitas Indonesia · 3 Components of an Algorithm 9Values and Variables Instruction (a.k.a. primitive) Sequence (of instructions) Procedure (involving

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

1

Components of an Algorithm

Adhi Harmoko S,M.Komp

2

RecallWhat is the problem solving process?

What is an algorithm?

What are some examples?

What are values and variables?

What are instructions or primitives?

3

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

Sequence (of instructions)Procedure (involving instructions) Selection (between instructions)Repetition (of instructions)

Documentation (beside instructions)

4

VariablesAre containers for values – places to store valuesExample:

This jarcan contain

10 cookies

50 grams of sugar

3 slices of cake

etc.

ValuesVariable

5

Restrictions on VariablesVariables may be restricted to contain a specific type of value

6

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

Sequence (of instructions)Procedure (involving instructions) Selection (between instructions)Repetition (of instructions)

Documentation (beside instructions)

7

Instructions (Primitives)Some action that is

simpleunambiguousthat the system knows about......and should be able to actually do

8

Instructions – ExamplesTake off your shoesCount to 10Cut along dotted lineKnit 1Purl 2Pull rip-cord firmlySift 10 grams of arsenic

Directions to perform specific actions on values and variables.

9

Instructions -- ApplicationSome instructions can only be applied to a specific type of values or variablesExamples:

10

Instructions (Primitives) --Recommendations

When writing an algorithm, make each instruction simpleand unambiguousExample:

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.

11

Instructions (Primitives) --Recommendations

When writing an algorithm, make each instruction simpleand unambiguousExample:

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

12

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

Sequence (of instructions)Procedure (involving instructions) Selection (between instructions)Repetition (of instructions)

Documentation (beside instructions)

13

SequenceA series of instructions...to be carried out one after the other......without hesitation or questionExample:

How to cook a Gourmet Meal™

14

Sequence -- Example1. Open freezer door2. Take out Gourmet Meal™3. Close freezer door4. Open microwave door5. Put Gourmet Meal™ on carousel6. Shut microwave door7. Set microwave on high for 5 minutes8. Start microwave9. Wait 5 minutes10.Open microwave door11.Remove Gourmet Meal™12.Close microwave door

15

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

Sequence (of instructions)Procedure (involving instructions) Selection (between instructions)Repetition (of instructions)

Documentation (beside instructions)

16

ProcedureA named sequence of instructionsSo that you can

Refer to it collectively (by name)...instead of individually (by each instruction in the sequence)

Example:Drive_To_University

17

Procedure -- Exampleprocedure Drive_To_Uni{1. find car keys2. disable car alarm3. open car door4. get in car5. shut car door6. put keys in ignition7. start car8. back car out of driveway9. drive to end of street10. turn right11. drive to end of street12. turn left...etc...etc...etc

...etc...etc...etc...52. find parking space53. pull into parking

space54. turn off engine55. remove keys from

ignition56. open car door57. get out58. shut car door59. lock car door60. enable alarm

}

18

Procedure – Example (cont)procedure Do_Wednesday{

Wake_upHave_ShowerEat_BreakfastDrive_To_UniSit_1301_Lecture...etc...etc...etc...Drive_From_Uni...etc...etc...etc...

}

procedure Do_Week{

Do_MondayDo_TuesdayDo_WednesdayDo_Thursday...etc...etc...etc...

}

19

Procedure – Example (cont)procedure Do_Wednesday{

Wake_upHave_ShowerEat_BreakfastDrive_To_UniSit_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-routineModuleFunction

20

Procedure – Example (cont)procedure Do_Wednesday{

Wake_upHave_ShowerEat_BreakfastDrive_To_UniSit_1301_Lecture...etc...etc...etc...Drive_From_Uni...etc...etc...etc...

}

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

21

Procedure – Example (cont)procedure Do_Wednesday{

Wake_upHave_ShowerEat_BreakfastDrive_To_UniSit_1301_Lecture...etc...etc...etc...Drive_From_Uni...etc...etc...etc...

}

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

22

ProcedureA 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” )

23

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

Sequence (of instructions)Procedure (involving instructions) Selection (between instructions)Repetition (of instructions)

Documentation (beside instructions)

24

SelectionAn instruction that decides which of two possible sequences is executedThe decision is based on a single true/false conditionExamples:

Car repairReciprocals

25

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

}else {CheckDistributorCheckIgnitionCoil

}

26

Selection Example – Car Repair (cont)if (motor turns) then {CheckFuelCheckSparkPlugsCheckCarburettor

}else {CheckDistributorCheckIgnitionCoil

}

Should be a true or false condition.

27

Selection Example – Car Repair (cont)if (motor turns) then{CheckFuelCheckSparkPlugsCheckCarburettor

}else {CheckDistributorCheckIgnitionCoil

}

Sequence if the condition is true.

28

Selection Example – Car Repair (cont)if (motor turns) then {CheckFuelCheckSparkPlugsCheckCarburettor

}else {CheckDistributorCheckIgnitionCoil

}

Sequence if the condition is false.

29

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”

30

Selection Example – Reciprocals (cont)

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

if (Num is not equal 0)then{

output 1/Num}else{

output "infinity“}

Algorithm:

31

Selection Example – Reciprocals (cont)

input Numif (Num is not equal 0)then{

output 1/Num}else{

output "infinity“}

Algorithm:

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

32

Selection Example – Reciprocals (cont)

input Numif (Num is not equal 0)then{

output 1/Num}else{

output "infinity“}

Algorithm:

Condition depends on the value of Num

33

Selection Example – Reciprocals (cont)

input Numif (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

34

Selection Example – Reciprocals (cont)

input Numif (Num is not equal 0)then{

output 1/Num}else{

output "infinity“}

Algorithm:

Executed if Num is notequal to 0

35

Selection Example – Reciprocals (cont)

input Numif (Num is not equal 0)then{

output 1/Num}else{

output "infinity“}

Algorithm:

Executed if Num is equal to 0

36

Selection -- Exercise

input Numif (Num is not equal 0)then{

output 1/Num}else{

output "infinity"}

Will the following algorithms produce the same output?

Algorithm 1:input Numif (Num is not equal 0)then{

output 1/Num}

output "infinity"

Algorithm 2:

37

Selection – Several ConditionsWhat if several conditions need to be satisfied?

if (today is Thursday and the time is 04.00pm )then {

Go to Computer 1 Lecture }else {

Go to Library}

Solution 1

38

Selection – Several Conditions (cont)

if ( today is Thursday ) then {

if ( the time is 04.00am )then

{Go to Computer 1 Lecture

}}else ...etc...etc...etc...

Solution 2

Often called a “nested selection”

39

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}

40

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

Sequence (of instructions)Procedure (involving instructions) Selection (between instructions)Repetition (of instructions)

Documentation (beside instructions)

41

RepetitionRepeat an instruction...

...while (or maybe until) some true or false condition occursTest the condition each time before repeating the instruction

Also known as iteration or loopExample:

Algorithm for getting a date

42

Repetition -- Example

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 ( )

}}

43

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

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 ( )

}} Sequence may not get

executed at all

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 ( )

}}

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

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 the variables used in the conditions are updated in each iteration

47

Repetition – Example (cont)What if we don’t increment the begging count?

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

48

Repetition – Variation

decide on Time and Locationinitialise booking to “unsuccessful”while ( not successfully booked ){get next Name in little black bookAskOnDate(Name, Time, Location)DetermineBookingSuccess

}SighWithRelief

49

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

Sequence (of instructions)Procedure (involving instructions) Selection (between instructions)Repetition (of instructions)

Documentation (beside instructions)

50

DocumentationRecords what the algorithm doesDescribes how it does itExplains the purpose of each component of the algorithmNotes restrictions or expectationsExample:

Getting a date (again)

51

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 bookAskOnDate(Name, Time, Location)DetermineBookingSuccess

}Assumes that I will find someone in the book before it

runs outSighWithRelief

52

The Software Development ProcessDefine the problem clearlyAnalyse the problem thoroughlyDesign an algorithm carefullyCode the algorithm efficientlyTest the code thoroughlyDocument the system lucidly

53

Top-down Algorithm DesignWrite down what you have to doBreak that into 3-7 smaller stepsBreak each step into 3-7 smaller stepsKeeping subdividing until each individual step is easy enough to do – i.e., until it is a single instructionExample:

Learning

54

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

documentRecord insights