DAA Lecture 2
DAA Lecture 2
Lecture # 2
In the 9th century Al Kho-war-iz-mi a 9th century Persian mathematician defined and
algorithm as such;
1. an ordered sequence means that you can number the steps (it's socks then shoes!)
2. unambiguous and well-defined instructions means that each instruction is clear, do-able,
and can be done without difficulty
3. performs some task
4. halts in finite time (algorithms terminate!)
Three categories of Algorithm Operations
Algorithmic operations are ordered in that there is a first instruction, a second instruction etc. However, this is not
enough. An algorithm must have the ability to alter the order of its instructions. An instruction that alters the order of
an algorithm is called a control structure
1. Number each instruction. This is to enforce the notion of an ordered sequence of operations. Furthermore we
introduce a dot notation (e.g. 3.1 come after 3 but before 4) to number subordinate operations for conditional and
iterative operations
2. Each instruction should be unambiguous (that is the computing agent, in this case the reader, is capable of carrying
out the instruction) and effectively computable (do-able).
3. Completeness. Nothing is left out.
Pseudo-code is best understood by looking at examples. Each following example demonstrates some of the control
structures used in algorithms, i.e sequential, conditional and iterative operations.
Example 1
Compute the final sales price of an item after factoring in sales tax. So w need three types of instructions: input (get),
process/calculate (=) and output (display)
CalculateFinalPrice
Input: p= price of item, str = sales tax rate
Output: fp = final price
1. start
2. get p
3. get str
4. sales tax = p * str
5. fp = p + sales tax
6. display fp
7. end
Variables: price of item, sales tax rate, sales tax, final price
Note that the operations are numbered and each operation is computable. We also extract and list all variables used in
our pseudo-code. This will be useful when translating pseudo-code into a programming language
Common Pseudo code statements;
Return: 10:48
You do
Example 2
Computing Weekly Wages: Gross pay depends on the pay rate and the number of hours worked per week. However,
if you work more than 40 hours, you get paid time-and-a-half for all hours worked over 40. Pseudo-code the task of
computing gross pay given pay rate and hours worked.
Example 3
Computing a Quiz Average: Pseudo-code a routine to calculate your quiz average. (no of quizzes, individual scores in
quizzes)
Suggested Solution for Example 2
Computing Weekly Wages: Gross pay depends on the pay rate and the number of hours worked per week. However, if you
work more than 40 hours, you get paid time-and-a-half for all hours worked over 40. Pseudo-code the task of computing
gross pay given pay rate and hours worked.
CalculateWeeklyWages
Input: hours worked, pay rate
Output: gross pay
START
1. get hours worked
2. get pay rate
3. if hours worked ≤ 40 then
3.1 gross pay = pay rate times hours worked
4. else
4.1 gross pay = pay rate times 40 plus 1.5 times pay rate times (hours worked minus 40)
5. display gross pay
END
TASK: Make this pseudocode better readable based on Example 1 solution format.
Suggested Solution Example 3
Computing a Quiz Average: Pseudo-code a routine to calculate your quiz average.
1. get number of quizzes
2. sum = 0
3. count = 0
4. while count < number of quizzes
4.1 get quiz grade
4.2 sum = sum + quiz grade
4.3 count = count + 1
5. average = sum / number of quizzes
6. display average
7. halt
TASK: Make this pseudocode better readable based on Example 1 solution format.
Pseudo Code Summary
Pseudo-code Language Constructions : A Summary Conditional (dot notation used for numbering subordinate
statements)
Computation/Assignment if "condition"
(subordinate) statement 1
set the value of "variable" to :"arithmetic expression" or
etc ...
"variable" equals "expression" or else
"variable" = "expression" (subordinate) statement 2
etc ...
Input/Output Iterative (dot notation used for numbering subordinate
statements)
get "variable", "variable", ...
while "condition"
display "variable", "variable", ...
(subordinate) statement 1
etc ...
IF THEN ELSE
Binary choice on a given Boolean condition is indicated by the use of four keywords: IF, THEN, ELSE,
and ENDIF. The general form is:
IF condition THEN
sequence 1
ELSE
sequence 2
ENDIF
The ELSE keyword and "sequence 2" are optional. If the condition is true, sequence 1 is performed,
otherwise sequence 2 is performed.
Example
IF HoursWorked > NormalMax THEN
Display overtime message
ELSE
Display regular time message
ENDIF
More Examples
b. Given a person’s birthday, write an algorithm that calculates their age and
decides if they are allowed to drive or not, assuming the legal age for driving
is 16.
Suggested Solutions
a. The operation involved in withdrawing money from your bank account. b. Given a person’s birthday, write an algorithm that calculates their
WithdrawMoney age and decides if they are allowed to drive or not assuming the legal
Input: Card details and pinNumber age for driving is 16.
Output: Dispense cash
BEGIN CanDrive
Enter your card Input: BirthDate
Enter pinNumber Output: allowed to drive, yes/no
IF pinNumber is Valid THEN
Prompt Amount BEGIN
IF (required_amount is in list)
Enter DOB
Select required_amount
age = Today - DOB
ELSE
Read required_amount IF age >= 16 THEN
END IF Print Allowed to drive
Dispense Cash ELSE
ELSE Print Not Allowed to drive
Prompt user to enter correct PinNumber END IF
and try again
END
END IF
END
Another Examples
Write an algorithm to award a student’s grade as either FAIL, PASS, MERIT, DISTINCTION based on the
following criteria:
FAIL 0 -39%
PASS: 40 – 49%
MERIT: 50 – 69%
DISTINCTION: 70 – 100%
GradeScore
Input: Student score
Output: Contextual grade
BEGIN
Enter score in percentage
IF score <=39 THEN
grade = FAIL
Suggested Solutions ELSE IF score >=40 AND <=49 THEN
grade = PASS
ELSE IF score >=50 AND <=69 THEN
grade = MERIT
ELSE
grade = DISTINCTION
END IF
END
WHILE
The WHILE construct is used to specify a loop with a test at the top. The beginning and ending of the loop
are indicated by two keywords WHILE and ENDWHILE. The general form is:
WHILE condition
sequence
ENDWHILE
The loop is entered only if the condition is true. The "sequence" is performed for each iteration. At the end
of each iteration, the condition is evaluated and the loop continues as long as the condition is true.
Example
ENDWHILE
Example
ENDWHILE
More Examples (Cont.)
Write an algorithm using iteration to find the value of xn where x is any integer and n >=0.
Power
Input: A number x and power n to be raised
Output: result, x raised to the power of n
BEGIN
Suggested Solution Enter the number x and the power n
result = 1
WHILE n != 0
result = result*x
n = n-1
END WHILE
RETURN Result
END
More Examples (Cont.)
This loop is similar to the WHILE loop except that the test is performed at the bottom of the loop instead of at the
top. Two keywords, REPEAT and UNTIL are used. The general form is:
REPEAT
sequence
UNTIL condition
The "sequence" in this type of loop is always performed at least once, because the test is performed after the
sequence is executed. At the conclusion of each iteration, the condition is evaluated, and the loop repeats if the
condition is false. The loop terminates when the condition becomes true.
FOR
This loop is a specialized construct for iterating a specific number of times, often called a "counting" loop. Two
keywords, FOR and ENDFOR are used. The general form is:
FOR iteration bounds
sequence
ENDFOR
In cases where the loop constraints can be obviously inferred it is best to describe the loop using problem
domain vocabulary.
Example
MaxGrade MinGrade
input: grades and number of students (n) input: grades and number of students (n)
Output: the maximum grade Output: the minimum grade
BEGIN BEGIN
Enter number of students n Enter number of students n
FOR i = 0 To n - 1 FOR i = 0 To n - 1
Enter grade[i] Enter grade[i]
END FOR END FOR
max = grade[0] min = grade[0]
FOR i = 1 To n - 1 FOR i = 1 To n - 1
IF grade[i] > max THEN IF grade[i] < min THEN
max = grade[i] min = grade[i]
END IF END IF
END FOR END FOR
RETURN max RETURN min
END END
More Examples
"Adequate" "Better"
Set moveCount to 1
FOR X = 1 to 10
FOR each row on the board
FOR Y = 1 to 10
FOR each column on the board
IF gameBoard[X][Y] = 0
IF gameBoard position (row, column) is
Do nothing
occupied THEN
ELSE
CALL findAdjacentTiles with row,
CALL theCall(X, Y) (recursive
column
method)
INCREMENT moveCount
increment counter
END IF
END IF
END FOR
END FOR
END FOR
END FOR
What have we covered in Introduction
• What is an Algorithm