Chapter 2
Algorithm Discovery
and Design
Question from last week…
▰ When would an infinite loop be
okay?
▻ Web Server
▻ User input expected until it
exists
▻ Games
▻ Music loop
Learning Objectives
▰ Explain the benefits of pseudocode over
natural language or a programming
language
▰ Represent algorithms using pseudocode
▰ Identify algorithm statements as sequential,
conditional, or iterative
▰ Define abstraction and top-down design,
and explain their use in breaking down
complex problems
Learning Objectives
▰ Illustrate the operation of algorithms
for:
▻ Multiplication by repeated addition
▻ Sequential search of a collection
of values
▻ Finding the maximum element in a
collection
▻ Finding a pattern string in a larger
piece of text
Introduction
▰ Everyday algorithms, such as hair washing, may
not be suitable for computers to perform (as in
Chapter 1).
▰ Algorithmic problem-solving focuses on
algorithms suitable for computers such as
searching lists and matching patterns.
▰ Pseudocode is a tool for designing algorithms but
does not run on a computing device.
▰ This chapter will use a set of problems to
illustrate algorithmic problem solving, including
those with conditional statements and loops.
Representing Algorithms
▰ Natural language is:
▻ Expressive and easy to use
▻ Verbose, unstructured, and ambiguous
▰ Programming languages are:
▻ Structured and designed for computers
▻ Grammatically fussy and cryptic
▰ Pseudocode lies somewhere between
these two and is used to design algorithms
prior to coding them
Representing Algorithms Natural
Language
FIGURE 2.1
Initially, set the value of the variable carry to 0 and the value of the
variable i to 0. When these initializations have been completed, begin
looping as long as the value of the variable i is less than or equal to (m –
1). First, add together the values of the two digits and and the current
value of the carry digit to get the result called . Now check the value
of to see whether it is greater than or equal to 10. If is greater than or
equal to 10, then reset the value of carry to 1 and reduce the value
of by 10; otherwise, set the value of carry to 0. When you are finished
with that operation, add 1 to i and begin the loop all over again. When
the loop has completed execution, set the leftmost digit of the result to
the value of carry and print out the final result, which consists of the
digits . After printing the result, the algorithm is finished, and it
terminates.
Representing Algorithms Programming Language
From Last Week
▰ What is…
▻ Sequential
▻ Conditional
▻ Iterative
Operations used to construct algorithms:
Sequential Conditional Iterative
operations operations operations
Looping
Ask a question instructions
and the next that tell not to
Carries out a operation is go on but go
single well- then selected back and
defined task on the basis of repeat the
the answer to execution of a
that question previous block
of instructions
Representing Algorithms
▰ Sequential operations perform a single task
▰ The three basic sequential operations:
▻ Computation: a single numeric calculation
▻ Input: gets data values from outside the algorithm
▻ Output: sends data values to the outside world
▰ A sequential algorithm is made up only of sequential
operations
▰ A variable is a named storage location to hold a data value
▰ Example: computing average miles per gallon
Let’s Try One…
An algorithm that gets five test scores, values
a, b, c, d, e as input and outputs the average
of those five values.
Step Operation
1 Get values for a,
b, c, d, e
2 Set the value
of average to
(a+b+c+d+e)/5
3 Print the value
of average
4 Stop
Representing Algorithms Sequential Algorithm
Step Operation
1 Get values for gallons used, starting mileage, ending mileage
2 Set value of distance driven to (ending mileage - starting
mileage)
3 Set value of average miles per gallon to (distance driven ÷
gallons used)
4 Print the value of average miles per gallon
5 Stop
Representing Algorithms
▰ Control operation: changes the normal flow of control
▰ Conditional statement: asks a question and selects
among alternative options:
1. Evaluate the true/false condition
2. If the condition is true, then do the first set of
operations and skip the second set
3. If the condition is false, skip the first set of
operations and do the second set
Let’s Revisit
An algorithm that gets five test scores, values
a, b, c, d, e as input and outputs the average
of those five values. If the average score is <
50 notify the user
Step to retake the class
Operation
1 Get values for a, b, c, d, e
2 Set the value of average to
(a+b+c+d+e)/5
3 If average score < 50 then
4 Print the message Not
Passing
5 Else
Print the average
6 Stop
Representing Algorithms Conditional
Statement
Representing Algorithms
▰ Iteration: an operation that causes
looping, repeating a block of
instructions
▰ While statement repeats while a
condition remains true
▻ Continuation condition: a test to
see if while loop should continue
▻ Loop body: instructions to
perform repeatedly
▰ Example: repeated mileage
calculations
Representing Algorithms Iteration and Loop
Body
Representing Algorithms
▰ Do/while, alternate iterative
operation
▻ Continuation condition
appears at the end
▻ Loop body always performed
at least once
▰ Primitive operations: sequential,
conditional, and iterative are all
that is needed
Representing Algorithms Do/While Posttest Loop
Examples of Algorithmic Problem-Solving
Looking, Looking, Looking
Assume that we have a list of 10,000
names that we define as N1, N2, N3, … ,
N10,000, along with the 10,000 telephone
numbers of those individuals, denoted as
T1, T2, T3, … , T10,000. To simplify the
problem, we initially assume that all
names in the book are unique and that
the names need not be in alphabetical
order.
Examples of Algorithmic Problem-
Solving
Looking, Looking, Looking
▰ Three versions here illustrate
algorithm discovery, working
toward a correct, efficient solution:
▻ A sequential algorithm (no loops
or conditionals)
▻ An incomplete iterative
algorithm
▻ A correct algorithm
Examples of Algorithmic Problem-
Solving
Big, Bigger, Biggest
▰ Library: A collection of prewritten,
useful algorithms
▰ A “building-block” algorithm used in
many libraries:
Given a value n ≥ 1 and a list containing
exactly n unique numbers called A1, A2,
… , An, find and print out both the
largest value in the list and the position
in the list where that largest value
occurred.
Examples of Algorithmic Problem-
Solving
Meeting Your Match
▰ Pattern matching: common across many applications,
such as:
▻ Word processor search, web search, image analysis,
and human genome project
▰ Let’s formally define the pattern-matching problem as
follows:
▻ You will be given some text composed of n characters
that will be referred to as T1 T2 … Tn. You will also be
given a pattern of m characters, m ≤ n, that will be
represented as P1 P2 … Pm. The algorithm must locate
every occurrence of the given pattern within the text.
The output of the algorithm is the location in the text
where each match occurred.
Examples of Algorithmic Problem-
Solving
Meeting Your Match
▰ Algorithm has two parts:
1. Sliding the pattern along the text, aligning
it with each position in turn
2. Given a particular alignment, determine if
there is a match at that location
▰ Solve parts separately and use
▻ Abstraction: focus on high level, not
details
▻ Top-down design: start with big picture,
gradually elaborate parts
Pattern Matching making sense
▰ T = CAT
▰ P=
DOGJONESCOWCAT
▰ T = CAT
▰ P=
BEARDEDDRAGONPIG
COW
Practice Time
Examples of Algorithmic Problem Solving
Go Forth and Multiply
Given two nonnegative
integer values, a ≥ 0, b ≥
0, compute and output
the product (a × b) using
the technique of repeated
addition. That is,
determine the value of
the sum a + a + a + … + a
(b times).
Examples of Algorithmic Problem-
Solving
Go Forth and Multiply
▰ Get input values
▻ Get values for a and b
▰ Compute the answer
▻ Loop b times, adding each time*
▰ Output the result
▻ Print the final value*
* steps need elaboration
Examples of Algorithmic Go Forth and
Multiply
▰ Loop b times, adding each time
▻ Get values for a and b
▻ Set the value of count to 0
▻ Set the value of product to 0
▻ While (count < b) do
▻ Set the value of product to (product + a)
▻ Set the value of count to (count + 1)
▻ End of the loop
▰ Output the result
▻ Print the value of product
A = 5, B=2
Step 1 if A or B = 0
Then set product to = 0 and go to Step 3
Else Set count to 0 and Set Product to 0 and Go to Step 2
Step 2 While Count < B (0 <2)
Set Product to (Product + A) (5 + 0)
Set Count to (Count + 1) (count = 1)
End of Loop
Step 2 While Count < B (1 <2)
Set Product to (Product + A) (5 + 5)
Set Count to (Count + 1) (count = 2)
End of Loop
Step 2 While Count < B (2 <2)
End of Loop
Step 3 Print the value of Product (10)
Step 4 Stop
Smallest Number
▰STEP 1 Set Largest# to Num-1
▰STEP 2 If Largest# < Num-2
▻ Then Set Largest # to Num-2 and Go To Step 3
▻ Else Go To Step 3
▰STEP 3 If Largest# < Num-3
▻ Then Set Largest# to Num-3 and Go To Step 4
▻ Else Go To Step 4
▰STEP 4 If Largest# < Num-4
▻ Then Set Largest# to Num-4 and Go To Step 5
▻ Else Go To Step 5
▰STEP 5 If Largest# < Num-5
▻ Then Set Largest# to Num-5 and Go To Step 6
▻ Else Go To Step 6
▰STEP 6 Print “The largest number is” Largest#
▰STEP 7 Stop Program
Values
▰ A1 = 2
▰ A2 = 15
▰ A3 = 6
▰ A4 = 25
▰ List Size = 4
▰ Largest = 2
Year = 2024
▰ Get YEAR
▰ STEP 1 If YEAR is equally divisible by 4; Result: [ Select ]
▰ Then Go To STEP 2;
▰ Else Go To STEP 5
▰ STEP 2 If YEAR is equally divisible by 100; Result: [ Select ]
▰ Then Go To STEP 3;
▰ Else Go To STEP 4
▰ STEP 3 If YEAR is equally divisible by 400; Result: [ Select ]
▰ Then Go To STEP 4;
▰ Else Go To STEP 5
▰ STEP 4 Print “The year is a Leap Year.” And Go To STEP 6
▰ STEP 5 Print “The year is not a Leap Year.” And Go To STEP 6
▰ STEP 6 Stop
Year = 1996
▰ Get YEAR
▰ STEP 1 If YEAR is equally divisible by 4; Result: [ Select ]
▰ Then Go To STEP 2;
▰ Else Go To STEP 5
▰ STEP 2 If YEAR is equally divisible by 100; Result: [ Select ]
▰ Then Go To STEP 3;
▰ Else Go To STEP 4
▰ STEP 3 If YEAR is equally divisible by 400; Result: [ Select ]
▰ Then Go To STEP 4;
▰ Else Go To STEP 5
▰ STEP 4 Print “The year is a Leap Year.” And Go To STEP 6
▰ STEP 5 Print “The year is not a Leap Year.” And Go To STEP 6
▰ STEP 6 Stop
Summary
▰ Pseudocode is used for algorithm design:
structured like code but allows English and
mathematical phrasing and notation
▰ Pseudocode is made up of sequential,
conditional, and iterative operations
▰ Algorithmic problem solving involves:
▻ Step-by-step development of algorithm
pieces
▻ Use of abstraction and top-down design