cmput101 introduction to computing(c) yngvi bjornsson & jia you1 algorithm discovery and design...

54
CMPUT101 Introduction to Compu ting (c) Yngvi Bjornsson & Jia You 1 Algorithm Discovery Algorithm Discovery and Design and Design Chapter 2 Chapter 2 Topics: Topics: Representing Algorithms Representing Algorithms Algorithmic Problem Algorithmic Problem Solving Solving

Post on 19-Dec-2015

224 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 1

Algorithm Discovery and Algorithm Discovery and DesignDesign

Chapter 2Chapter 2Topics:Topics:

Representing AlgorithmsRepresenting AlgorithmsAlgorithmic Problem SolvingAlgorithmic Problem Solving

Page 2: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 2

Why are Algorithms Why are Algorithms Important?Important?

If we can discover an algorithm to perform a task, we If we can discover an algorithm to perform a task, we can instruct a can instruct a computing agentcomputing agent to execute it and solve to execute it and solve

the problem for us.the problem for us.

If we can discover an algorithm to perform a task, we If we can discover an algorithm to perform a task, we can instruct a can instruct a computing agentcomputing agent to execute it and solve to execute it and solve

the problem for us.the problem for us.

Page 3: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 3

Representing AlgorithmsRepresenting Algorithms

• What language to use?What language to use?– Expressive.Expressive.– Clear, presice, and unambiguous.Clear, presice, and unambiguous.

• For example, we could use:For example, we could use:– Natural language (e.g. English).Natural language (e.g. English).– Formal programming languages (e.g. C++).Formal programming languages (e.g. C++).– Something else?Something else?

Page 4: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 4

141444

Example: Adding 2 Example: Adding 2 numbersnumbers

11 88 2222 66 33

44 55____________________

++

11

•Assume we know how to add 2 single digit Assume we know how to add 2 single digit numbers, but want to write an algorithm to add numbers, but want to write an algorithm to add any 2 numbers:any 2 numbers:

Page 5: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 5

Example using Natural Example using Natural LanguageLanguage

Initially, set the value of the variable carry to 0. Initially, set the value of the variable carry to 0. When these initializations have been completed, When these initializations have been completed, begin looping until the value of the variable i begin looping until the value of the variable i becomes greater than m-1. First add together becomes greater than m-1. First add together the values of the two digits athe values of the two digits aii and b and bii and the and the

current value of the carry digit to get the result current value of the carry digit to get the result called ccalled cii. Now check the value of c. Now check the value of c ii to see to see

whether it is greater than or equal to 10. If cwhether it is greater than or equal to 10. If c ii is is

greater than or equal to 10, then ...greater than or equal to 10, then ...

Initially, set the value of the variable carry to 0. Initially, set the value of the variable carry to 0. When these initializations have been completed, When these initializations have been completed, begin looping until the value of the variable i begin looping until the value of the variable i becomes greater than m-1. First add together becomes greater than m-1. First add together the values of the two digits athe values of the two digits aii and b and bii and the and the

current value of the carry digit to get the result current value of the carry digit to get the result called ccalled cii. Now check the value of c. Now check the value of c ii to see to see

whether it is greater than or equal to 10. If cwhether it is greater than or equal to 10. If c ii is is

greater than or equal to 10, then ...greater than or equal to 10, then ...

Page 6: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 6

Natural LanguagesNatural Languages

• English or some other natural language.English or some other natural language.• Are Are notnot particularly good: particularly good:

– too verbosetoo verbose– unstructuredunstructured– too rich in interpretation (ambiguous)too rich in interpretation (ambiguous)– impreciseimprecise

Page 7: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 7

Example using Example using Programming LanguageProgramming Language{ { int I, m, Carry;int I, m, Carry; int a[100], b[100], c[100];int a[100], b[100], c[100]; cin >> m;cin >> m; for ( int j = 0 ; k <= m-1 ; j++ ) {for ( int j = 0 ; k <= m-1 ; j++ ) { cin >> a[j];cin >> a[j]; cin >> b[j];cin >> b[j]; }} Carry = 0;Carry = 0; i = 0;i = 0; while ( i < m ) { …while ( i < m ) { …

{ { int I, m, Carry;int I, m, Carry; int a[100], b[100], c[100];int a[100], b[100], c[100]; cin >> m;cin >> m; for ( int j = 0 ; k <= m-1 ; j++ ) {for ( int j = 0 ; k <= m-1 ; j++ ) { cin >> a[j];cin >> a[j]; cin >> b[j];cin >> b[j]; }} Carry = 0;Carry = 0; i = 0;i = 0; while ( i < m ) { …while ( i < m ) { …

Page 8: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 8

Programming Programming LanguagesLanguages

• Are Are notnot particularly good either: particularly good either:– Too many implementation details to worry aboutToo many implementation details to worry about

– Too rigid syntaxToo rigid syntax

• Easy to lose sight of the real taskEasy to lose sight of the real task– We don't see the forest because of all the trees!We don't see the forest because of all the trees!

Page 9: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 9

Pseudo-codePseudo-code• We need a compromise between the two:We need a compromise between the two:

Pseudo-codePseudo-code• Computer scientists use pseudo-code to Computer scientists use pseudo-code to

express algorithms:express algorithms:– English like constructs (or other natural English like constructs (or other natural

language), butlanguage), but– modeled to look like statements in typical modeled to look like statements in typical

programming languages. programming languages.

Page 10: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 10

Pseudo-code for the Pseudo-code for the Addition AlgorithmAddition Algorithm

StepStep OperationOperation11 Get the value of aGet the value of am-1m-1, …, a, …, a00

22 Get the value of bGet the value of bm-1m-1, …, b, …, b00

33 Set the value of Set the value of carrycarry to 0 to 044 Set the value of Set the value of ii to 0 to 0 55 Repeat steps 6-8 until Repeat steps 6-8 until ii greater than greater than m-1m-166 Set the value of Set the value of ccii to to a aii + b + bii + carry + carry

77 IfIf c cii >= 10, >= 10, then setthen set c cii to c to cii - 10 - 10 andand carry carry to 1;to 1; otherwise set the value of otherwise set the value of carry carry to 0to 0

88 Set value of Set value of ii to to ii +1 (look at next digit) +1 (look at next digit)99 Set cSet cm m to to carrycarry

1010 Print out the final answer cPrint out the final answer cmm, c, cm-1m-1, … c, … c00 1111 Stop.Stop.

Page 11: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 11

What kind of operations What kind of operations do we need?do we need?

• Getting input and producing outputGetting input and producing output– Get the two numbersGet the two numbers– Display the outcomeDisplay the outcome

• Referring to values within our algorithmReferring to values within our algorithm– Add together the rightmost digits of the two numbersAdd together the rightmost digits of the two numbers– Add together aAdd together a00 and b and b00

• Doing something if some condition is trueDoing something if some condition is true– If the outcome is greater or equal to 10 then ...If the outcome is greater or equal to 10 then ...

• Doing something repeatedlyDoing something repeatedly– Do this for all the digits in the numbers ... Do this for all the digits in the numbers ...

Page 12: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 12

Pseudo-code PrimitivesPseudo-code PrimitivesThree basic kind of operations:Three basic kind of operations:• SequentialSequential

– Computation ( Set … )Computation ( Set … )– Input/Output ( Get ... / Print ... )Input/Output ( Get ... / Print ... )

• ConditionalConditional– If … ElseIf … Else– If …If …

• Iterative / loopingIterative / looping– Repeat ...Repeat ...– While ...While ...

Page 13: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 13

Performs a computation and stores the result.Performs a computation and stores the result.

ComputationComputation

Example:Example:

Set the value of Set the value of C to (A + B)C to (A + B)

Set the value of Set the value of locationlocation to 0 to 0

Set the value of Set the value of GPA to (sum / count)GPA to (sum / count)

General format:General format:

Set the value of <variable> to <expression>Set the value of <variable> to <expression> Set the value of <variable> to <expression>Set the value of <variable> to <expression>

Page 14: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 14

VariablesVariablesA A variablevariable is a named storage. is a named storage.

- A value can be stored into it, overwriting the - A value can be stored into it, overwriting the previous valueprevious value

- Its value can be copied- Its value can be copied ExamplesExamples::

Set the value of Set the value of AA to 3 to 3

The variable A holds the value 3 after its executionThe variable A holds the value 3 after its execution

Set the value of Set the value of AA to ( to (AA+1)+1)

Same as: add 1 to the value ofSame as: add 1 to the value of A A ( ( A A is now 4)is now 4)

Page 15: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 15

Not too Strict on SyntaxNot too Strict on Syntax• Pseudo-code is kind of a programming language Pseudo-code is kind of a programming language

without a rigid syntax, for example we can write:without a rigid syntax, for example we can write:– Set the value of A to (B+C) Set the value of A to (B+C)

• as as – Set A to (B+C)Set A to (B+C)

• Or even:Or even:• Set the value of Set the value of sumsum to 0 to 0• Set the value of Set the value of GPAGPA to 0 to 0

• as as • Set Set sumsum and and GPAGPA to 0 to 0

Page 16: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 16

• The computing agent (The computing agent (computercomputer) needs to ) needs to communicate with the outside world: communicate with the outside world:

– INPUTINPUT operations allow the computing agent to operations allow the computing agent to receive from the outside world data values to use receive from the outside world data values to use in subsequent computations.in subsequent computations.

– OUTPUTOUTPUT operations allow the computing agent operations allow the computing agent to communicate results of computations to the to communicate results of computations to the outside world.outside world.

Sequential Operations - Sequential Operations - Input/OutputInput/Output

Outside worldOutside world

InputInput

OutputOutput

Page 17: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 17

InputInputGeneral format:General format:

The computing agent (The computing agent (computercomputer) suspends) suspendsexecutions and waits for an input value.executions and waits for an input value.

Get a value for <variable>Get a value for <variable> Get a value for <variable>Get a value for <variable>

Page 18: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 18

Input - ExamplesInput - Examples• Examples:Examples:

– Get value for Get value for gradegrade– Get values for N, MGet values for N, M

• Can write:Can write:– Get value for NGet value for N11

– ......– Get value for NGet value for N100100

• asas– Get value for NGet value for N11,..., N,..., N100100

Page 19: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 19

OutputOutputGeneral format:General format:

The computing agent (The computing agent (computercomputer) displays the value of the ) displays the value of the variable(s).variable(s).

Print the value of <variable>Print the value of <variable>

Print the message, "<text>"Print the message, "<text>"

Print the value of <variable>Print the value of <variable>

Print the message, "<text>"Print the message, "<text>"

Page 20: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 20

Output - ExamplesOutput - Examples• Examples:Examples:

– Print the value of Print the value of gradegrade– Print the message, "Hello"Print the message, "Hello"

• Can write:Can write:– Print the value of NPrint the value of N11

– ......– Print the value of NPrint the value of N100100

• asas– Print the values of NPrint the values of N11,..., N,..., N100100

Page 21: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 21

ExampleExample• Write an algorithm to calculate the average of Write an algorithm to calculate the average of

three numbers.three numbers.

StepsSteps OperationsOperations

1 Get values for 1 Get values for N1N1, , N2N2, and , and N3N3

2 Set the value of 2 Set the value of AverageAverage to ( to (N1N1++N2N2++N3)N3)/3/3

3 Print the value of 3 Print the value of AverageAverage

4 Stop4 Stop

StepsSteps OperationsOperations

1 Get values for 1 Get values for N1N1, , N2N2, and , and N3N3

2 Set the value of 2 Set the value of AverageAverage to ( to (N1N1++N2N2++N3)N3)/3/3

3 Print the value of 3 Print the value of AverageAverage

4 Stop4 Stop

Page 22: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 22

Conditional OperationsConditional Operations

If <If <condition> condition> then then

operations for the then-partoperations for the then-part

ElseElse

operations for the else-partoperations for the else-part

If <If <condition> condition> then then

operations for the then-partoperations for the then-part

ElseElse

operations for the else-partoperations for the else-part1. Evaluate <condition> expression to see

whether it is true or false.

2. If true, then execute operations in then-part

3. Otherwise, execute operations in else-part.

Page 23: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 23

Conditions, or Boolean Conditions, or Boolean ExpressionsExpressions

• A A conditioncondition is one whose value is true or is one whose value is true or false, for example:false, for example:– 3 > 23 > 2 is greater than (true)is greater than (true)– 3 = 2 3 = 2 is equal to (false)is equal to (false)– AA > 2 > 2 is true if is true if AA’s value is ’s value is

greater greater than 2 (at the than 2 (at the time this is time this is executed), false otherwise.executed), false otherwise.

Page 24: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 24

E1 or E2E1 or E2

true if at least one of them is true; false true if at least one of them is true; false otherwise.otherwise.

E.g. 3 > 2 or 2 >3 is trueE.g. 3 > 2 or 2 >3 is true

E1 and E2E1 and E2

true if both are true; false otherwise true if both are true; false otherwise

E.g. 3 > 2 and 2 >3 is falseE.g. 3 > 2 and 2 >3 is false

not E not E

true if E is false, false if E is truetrue if E is false, false if E is true

Conditions may be Conditions may be compoundedcompounded

Page 25: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 25

1. Get a value for 1. Get a value for AA

2. If 2. If AA = 0 then = 0 then

3. Print the message, “The input is zero” 3. Print the message, “The input is zero”

Else Else

4. Print the message, “The input is not zero”4. Print the message, “The input is not zero”

1. Get a value for 1. Get a value for AA

2. If 2. If AA = 0 then = 0 then

3. Print the message, “The input is zero” 3. Print the message, “The input is zero”

Else Else

4. Print the message, “The input is not zero”4. Print the message, “The input is not zero”

ExampleExample

1. Get a value for 1. Get a value for gradegrade

2. If 2. If gradegrade < 1 or < 1 or gradegrade > 9 then > 9 then

3. Print the message, “Invalid grade” 3. Print the message, “Invalid grade”

Else Else

4. Set the value of 4. Set the value of total total to (to (grade + totalgrade + total))

1. Get a value for 1. Get a value for gradegrade

2. If 2. If gradegrade < 1 or < 1 or gradegrade > 9 then > 9 then

3. Print the message, “Invalid grade” 3. Print the message, “Invalid grade”

Else Else

4. Set the value of 4. Set the value of total total to (to (grade + totalgrade + total))

Page 26: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 26

Iterative Operations - Iterative Operations - RepeatRepeat

Repeat steps i to j until <condition> becomes trueRepeat steps i to j until <condition> becomes true step i:step i: operationoperation step i+1:step i+1: operationoperation …… step j:step j: operationoperation

1.1. Execute steps i to jExecute steps i to j2.2. Evaluate <condition>Evaluate <condition>3.3. If condition is false, go back to 1.If condition is false, go back to 1.4.4. Otherwise, continue execution from step j+1.Otherwise, continue execution from step j+1.

Page 27: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 27

1 Get a value for 1 Get a value for countcount

2 Repeat steps 3 to 5 until (2 Repeat steps 3 to 5 until (countcount >10) >10)

3 Set 3 Set squaresquare to ( to (countcount * * countcount))

4 Print the values of 4 Print the values of countcount and and squaresquare

5 Add 1 to 5 Add 1 to countcount

1 Get a value for 1 Get a value for countcount

2 Repeat steps 3 to 5 until (2 Repeat steps 3 to 5 until (countcount >10) >10)

3 Set 3 Set squaresquare to ( to (countcount * * countcount))

4 Print the values of 4 Print the values of countcount and and squaresquare

5 Add 1 to 5 Add 1 to countcount

ExampleExample

Page 28: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 28

What happens when it gets executed?What happens when it gets executed?

If initial value for If initial value for countcount is 8, we get printout is 8, we get printout

8 648 64

9 819 81

10 10010 100

What happens when it gets executed?What happens when it gets executed?

If initial value for If initial value for countcount is 8, we get printout is 8, we get printout

8 648 64

9 819 81

10 10010 100

Repeat LoopsRepeat Loops

Page 29: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 29

If initial value for If initial value for countcount is 11, we get printout is 11, we get printout

11 12111 121Why?Why?

Because the body is executed once before any Because the body is executed once before any test is done!test is done!

If need to execute loop 0 or more times we If need to execute loop 0 or more times we should use While-loops.should use While-loops.

If initial value for If initial value for countcount is 11, we get printout is 11, we get printout

11 12111 121Why?Why?

Because the body is executed once before any Because the body is executed once before any test is done!test is done!

If need to execute loop 0 or more times we If need to execute loop 0 or more times we should use While-loops.should use While-loops.

Repeat LoopsRepeat Loops

Page 30: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 30

Iterative Operation - Iterative Operation - WhileWhile

While <condition> remains true do steps i to jWhile <condition> remains true do steps i to j step i:step i: operationoperation step i+1:step i+1: operationoperation …… step j:step j: operationoperation

1.1. Evaluate <condition>Evaluate <condition>2.2. If condition is true, execute steps i to j, If condition is true, execute steps i to j,

then go back to 1.then go back to 1.3.3. Otherwise, if condition is false,continue Otherwise, if condition is false,continue

execution from step j+1.execution from step j+1.

Page 31: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 31

1 Get a value for 1 Get a value for countcount

2 While 2 While countcount < 10 do < 10 do

3 Set 3 Set squaresquare to ( to (countcount * * countcount))

4 Print the values of 4 Print the values of countcount and and squaresquare

5 Add 1 to 5 Add 1 to countcount

6 Stop6 Stop

1 Get a value for 1 Get a value for countcount

2 While 2 While countcount < 10 do < 10 do

3 Set 3 Set squaresquare to ( to (countcount * * countcount))

4 Print the values of 4 Print the values of countcount and and squaresquare

5 Add 1 to 5 Add 1 to countcount

6 Stop6 Stop

ExampleExample

Page 32: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 32

What happens when it gets executed?What happens when it gets executed?

If If countcount starts with 7, we get printout starts with 7, we get printout 7 497 49 8 648 64 9 819 81What if What if countcount starts with 11? starts with 11?

Nothing is printed, loop is executed 0 times.Nothing is printed, loop is executed 0 times.

What happens when it gets executed?What happens when it gets executed?

If If countcount starts with 7, we get printout starts with 7, we get printout 7 497 49 8 648 64 9 819 81What if What if countcount starts with 11? starts with 11?

Nothing is printed, loop is executed 0 times.Nothing is printed, loop is executed 0 times.

While LoopsWhile Loops

Page 33: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 33

StepsSteps Operations Operations

1 Get values for 1 Get values for NN and and MM

2 Set the value of 2 Set the value of ResultResult to 0 to 0

3 While 3 While MM > 0 do steps 4 and 5 > 0 do steps 4 and 5

4 Add 4 Add NN to the value of to the value of ResultResult

5 Subtract 1 from 5 Subtract 1 from MM

6 Print the value of 6 Print the value of ResultResult

7 7 StopStop

StepsSteps Operations Operations

1 Get values for 1 Get values for NN and and MM

2 Set the value of 2 Set the value of ResultResult to 0 to 0

3 While 3 While MM > 0 do steps 4 and 5 > 0 do steps 4 and 5

4 Add 4 Add NN to the value of to the value of ResultResult

5 Subtract 1 from 5 Subtract 1 from MM

6 Print the value of 6 Print the value of ResultResult

7 7 StopStop

Example: Multiply (via Example: Multiply (via addition)addition)

Page 34: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 34

Result: 0 Result: 0

3 3

66

99

12 12

Result: 0 Result: 0

3 3

66

99

12 12

N * M ExampleN * M Example

Suppose initially Suppose initially NN = 3 and = 3 and MM = 4. = 4. During computation, the variable During computation, the variable ResultResult held the following values, in that order:held the following values, in that order:

Page 35: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 35

DangerDanger::

A loop can be infinite due to non-changing conditions1A loop can be infinite due to non-changing conditions1

Example 1: Example 2:Example 1: Example 2:

Repeat until 2 > 3 While 3 > 2 do Repeat until 2 > 3 While 3 > 2 do

loop body loop bodyloop body loop body

2 > 3 is false all the time. 3 >2 true all the time.2 > 3 is false all the time. 3 >2 true all the time.

Infinite LoopsInfinite Loops

Page 36: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 36

1. Set the value of 1. Set the value of AA to 1 to 1

2. While 2. While AA is an odd number do is an odd number do

3. Add 2 to the value of 3. Add 2 to the value of AA

4. Print the value of 4. Print the value of AA

5. Stop 5. Stop

Even though we change A’s value, it does not change the fact that “A is an odd number”

1. Set the value of 1. Set the value of ii to 1 to 1

2. While 2. While i < 10i < 10 do step 3 do step 3

3. Print value of 3. Print value of ii

4. Stop4. Stop

Opppsss, we forgot to increase i

Why do these two algorithms not terminate?

Page 37: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 37

Addition Algorithm Addition Algorithm RevisitedRevisited

StepStep OperationOperation11 Get the value of aGet the value of am-1m-1, …, a, …, a00

22 Get the value of bGet the value of bm-1m-1, …, b, …, b00

33 Set the value of Set the value of carrycarry to 0 to 044 Set the value of Set the value of ii to 0 to 0 55 Repeat steps 6-8 until Repeat steps 6-8 until ii greater than greater than m-1m-166 Set the value of Set the value of ccii to to a aii + b + bii + carry + carry

77 IfIf c cii >= 10, >= 10, then setthen set c cii to c to cii - 10 - 10 andand carry carry to 1;to 1; otherwise set the value of otherwise set the value of carry carry to 0to 0

88 Set value of Set value of ii to to ii +1 (look at next digit) +1 (look at next digit)99 Set cSet cm m to to carrycarry

1010 Print out the final answer cPrint out the final answer cmm, c, cm-1m-1, … c, … c00 1111 Stop.Stop.

Page 38: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 38

Summary of PseudocodeSummary of PseudocodeSequentialSequential

Set the value of Set the value of variablevariable to to expressionexpression

Input and OutputInput and Output

Get a value ……; Print …...Get a value ……; Print …...

ConditionalConditional

If a If a conditioncondition is true then is true then

the first set of operationsthe first set of operations

else else the second set of operationsthe second set of operations

Page 39: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 39

Summary of Summary of PseudocodePseudocode

Iterative:Iterative:

Repeat until a condition becomes true Repeat until a condition becomes true the loop body the loop body

While a condition remains true do While a condition remains true do the loop body the loop body

Page 40: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 40

ExercisesExercises

Get values for Get values for x, y, zx, y, z

If If x x < 1 or < 1 or yy < 1 or < 1 or zz < 1 then < 1 then Print message, “Bad data”Print message, “Bad data” ElseElse Set Set AverageAverage to ( to (x + y + zx + y + z) / 3) / 3 Print the value of Print the value of AverageAverage

StopStop

Get values for Get values for x, y, zx, y, z

If If x x < 1 or < 1 or yy < 1 or < 1 or zz < 1 then < 1 then Print message, “Bad data”Print message, “Bad data” ElseElse Set Set AverageAverage to ( to (x + y + zx + y + z) / 3) / 3 Print the value of Print the value of AverageAverage

StopStop

I. Compute the average of 3 grades (1-9); if any one is 0 I. Compute the average of 3 grades (1-9); if any one is 0 or negative, a message “Bad data” is printedor negative, a message “Bad data” is printed

Page 41: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 41

Get value for Get value for nn, the number of integers, the number of integers Get values for Get values for II11, I, I22, …, I, …, In, n, a list ofa list of nn integers integers Set the value of Set the value of SumSum to 0 to 0 Set the value of Set the value of kk to 1 to 1 Repeat until Repeat until k > nk > n

Add Add IIkk to to SumSum Add 1 to Add 1 to kk

End of the loop End of the loop Print the value of Print the value of Sum Sum StopStop

Get value for Get value for nn, the number of integers, the number of integers Get values for Get values for II11, I, I22, …, I, …, In, n, a list ofa list of nn integers integers Set the value of Set the value of SumSum to 0 to 0 Set the value of Set the value of kk to 1 to 1 Repeat until Repeat until k > nk > n

Add Add IIkk to to SumSum Add 1 to Add 1 to kk

End of the loop End of the loop Print the value of Print the value of Sum Sum StopStop

II. II. Compute the sum of Compute the sum of nn integers where integers where nn > 0 > 0

ExercisesExercises

Page 42: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 42

Repeat until Repeat until AA > 0 > 0

Print message, “Enter an integer”Print message, “Enter an integer”

Get a value for Get a value for AA

End of the loopEnd of the loop

StopStop

Repeat until Repeat until AA > 0 > 0

Print message, “Enter an integer”Print message, “Enter an integer”

Get a value for Get a value for AA

End of the loopEnd of the loop

StopStop

III. What does the following algorithm do?III. What does the following algorithm do?

IV. Write an algorithm that does the same but using IV. Write an algorithm that does the same but using a while loop instead of a repeat loop.a while loop instead of a repeat loop.

ExercisesExercises

Page 43: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 43

RECALL: Algorithms & RECALL: Algorithms & Computing AgentsComputing Agents

If we can discover an algorithm to perform If we can discover an algorithm to perform a task, we can instruct a a task, we can instruct a computing agentcomputing agent to execute it to solve the problem for us.to execute it to solve the problem for us.

If we can discover an algorithm to perform If we can discover an algorithm to perform a task, we can instruct a a task, we can instruct a computing agentcomputing agent to execute it to solve the problem for us.to execute it to solve the problem for us.

Page 44: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 44

Algorithmic Algorithmic Problem SolvingProblem SolvingAlgorithm discoveryAlgorithm discovery

The process of finding a solution to a given problemThe process of finding a solution to a given problem

Typical Steps:Typical Steps:

1. Understand the problem1. Understand the problem

2. Divide it into sub-problems 2. Divide it into sub-problems

3. Sketch and refine, probably repeatedly 3. Sketch and refine, probably repeatedly

4. Test the correctness4. Test the correctness

Page 45: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 45

Find the Find the phone numberphone number of a given of a given NameName in an in an (unsorted) list of names and their phone numbers(unsorted) list of names and their phone numbers

NamesNames Phone numbersPhone numbers

NN11 TT11

NN22 TT22

……

NN10001000 TT10001000

Sequential search: an Sequential search: an ExampleExample

Page 46: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 46

1. Get values for 1. Get values for NameName, , NN11,…,N,…,N10001000, T, T11,…,T,…,T10001000

2. 2. If If Name = NName = N11 then print the value of then print the value of TT11

3. If 3. If Name = NName = N22 then print the value of then print the value of TT22

……1000. If 1000. If Name = NName = N999999 then print the value of then print the value of TT999999

1001. If Name = 1001. If Name = NN10001000 then print the value of then print the value of TT10001000

1002. Stop1002. Stop

Sequential search: 1st Sequential search: 1st AttemptAttempt

Page 47: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 47

Get values for Get values for NameName, , NN11,…, N,…, N10001000, T, T11,…, T,…, T10001000

Set the value Set the value ii to 1 and the value of to 1 and the value of FoundFound to NO to NORepeat until Repeat until Found = Found = YesYes oror i > 1000 i > 1000

IfIf Name = N Name = Nii thenthen Print the value ofPrint the value of T Tii

Set the value of Set the value of FoundFound to YES to YES ElseElse Add 1 to the value of Add 1 to the value of iiEnd of loopEnd of loop

StopStop

Get values for Get values for NameName, , NN11,…, N,…, N10001000, T, T11,…, T,…, T10001000

Set the value Set the value ii to 1 and the value of to 1 and the value of FoundFound to NO to NORepeat until Repeat until Found = Found = YesYes oror i > 1000 i > 1000

IfIf Name = N Name = Nii thenthen Print the value ofPrint the value of T Tii

Set the value of Set the value of FoundFound to YES to YES ElseElse Add 1 to the value of Add 1 to the value of iiEnd of loopEnd of loop

StopStop

Sequential search: Sequential search: Using A LoopUsing A Loop

Page 48: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 48

Location A1 A2 A3 A4 A5 A6 A7

Value 5 2 8 4 8 6 4

The largest is 8 at location 3The largest is 8 at location 3

Idea (sketch): Go through the entire list, at each Idea (sketch): Go through the entire list, at each iteration find the iteration find the largest-so-farlargest-so-far and record its and record its locationlocation

Given a list of variables Given a list of variables AA11, A, A22, …, A, …, Ann, find the , find the largest value and its (first) locationlargest value and its (first) location

Selection: Find The Selection: Find The Largest NumberLargest Number

Page 49: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 49

Location A1 A2 A3 A4 A5 A6 A7

Value 5 2 8 4 8 6 4

To begin with, To begin with, set set largest-so-farlargest-so-far to (the value of) to (the value of) A1A1set set locationlocation to 1 to 1set set ii to 2 to 2

i

Page 50: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 50

Location A1 A2 A3 A4 A5 A6 A7

Value 5 2 8 4 8 6 4

Compare Compare A1A1 and and A2A2 largest-so-farlargest-so-far still holds the value of still holds the value of A1A1set set ii to to ii+1+1

i

Page 51: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 51

Location A1 A2 A3 A4 A5 A6 A7

Value 5 2 8 4 8 6 4

Compare Compare A1A1 and and A3A3largest-so-farlargest-so-far now holds the value of now holds the value of A3A3locationlocation is 3 is 3set set ii to to ii+1+1

i

Page 52: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 52

Location A1 A2 A3 A4 A5 A6 A7

Value 5 2 8 4 8 6 4

i

Continue the similar process until Continue the similar process until ii = 8= 8

Page 53: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 53

Get a value for Get a value for nn, the size of the list, the size of the listGet values for Get values for AA11, A, A22, …, A, …, An, n, the list to be searchedthe list to be searchedSet Set largest_so_farlargest_so_far to to AA1 1 andand setset locationlocation to 1 to 1Set the value of Set the value of ii to 2 to 2While While ii is less or equal to is less or equal to nn do do If If AAii > > largest_so_farlargest_so_far then then Set the value of Set the value of largest_so_farlargest_so_far to to AAii

Set the value of Set the value of locationlocation to to ii Add 1 to the value of Add 1 to the value of iiEnd of loopEnd of loopPrint the values of Print the values of largest_so_farlargest_so_far and and locationlocation

Get a value for Get a value for nn, the size of the list, the size of the listGet values for Get values for AA11, A, A22, …, A, …, An, n, the list to be searchedthe list to be searchedSet Set largest_so_farlargest_so_far to to AA1 1 andand setset locationlocation to 1 to 1Set the value of Set the value of ii to 2 to 2While While ii is less or equal to is less or equal to nn do do If If AAii > > largest_so_farlargest_so_far then then Set the value of Set the value of largest_so_farlargest_so_far to to AAii

Set the value of Set the value of locationlocation to to ii Add 1 to the value of Add 1 to the value of iiEnd of loopEnd of loopPrint the values of Print the values of largest_so_farlargest_so_far and and locationlocation

Selection: Find The Selection: Find The Largest NumberLargest Number

Page 54: CMPUT101 Introduction to Computing(c) Yngvi Bjornsson & Jia You1 Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem

CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 54

Two examples of algorithmic problem Two examples of algorithmic problem solvingsolving

• Sequential searchSequential search

Q: On the average, how many comparisons (of Q: On the average, how many comparisons (of names) does the algorithm make?names) does the algorithm make?• SelectionSelection

Q: Design a similar algorithm to find Q: Design a similar algorithm to find -the smallest value and its first location-the smallest value and its first location -the largest and all the locations holding it-the largest and all the locations holding it

Algorithmic Problem Algorithmic Problem Solving: SummarySolving: Summary