0% found this document useful (0 votes)
63 views

DAA Lecture 2

Here is a suggested algorithm to award a student's grade based on their score: ELSE IF score >=50 AND <=69 THEN grade = MERIT ELSE IF score >=70 AND <=100 THEN grade = DISTINCTION ELSE Print "Invalid score" END IF Print "Your grade is:", grade END This uses nested IF/ELSE statements to check the student's score against the different grade boundaries and assign the appropriate grade label. It also has a final ELSE to catch any invalid scores outside the 0-100% range.

Uploaded by

Aqsa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

DAA Lecture 2

Here is a suggested algorithm to award a student's grade based on their score: ELSE IF score >=50 AND <=69 THEN grade = MERIT ELSE IF score >=70 AND <=100 THEN grade = DISTINCTION ELSE Print "Invalid score" END IF Print "Your grade is:", grade END This uses nested IF/ELSE statements to check the student's score against the different grade boundaries and assign the appropriate grade label. It also has a final ELSE to catch any invalid scores outside the 0-100% range.

Uploaded by

Aqsa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Design & Analysis of Algorithms

Lecture # 2

Introduction to Algorithms &


Pseudo-code
Design & Analysis of Algorithm
What is an algorithm?

In the 9th century Al Kho-war-iz-mi a 9th century Persian mathematician defined and
algorithm as such;

An ordered sequence of unambiguous and well-defined instructions that performs


some task and halts in finite time
So what did Al Khowarizmi actually mean?

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

Three Categories of Algorithmic Operations:

1. sequential operations - instructions are executed in order


2. conditional ("question asking") operations - a control structure that asks a true/false question and then selects the
next instruction based on the answer
3. iterative operations (loops) - a control structure that repeats the execution of a block of instructions
What is Pseudo code?
Pseudo-Code is a numbered list of instructions to perform some task. In this module we will suggest three standards for
good pseudo code practise.

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;

If, then, else, endif, select, while,

endwhile, case, others for and get.

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

variables: number of quizzes, sum ,count, quiz grade, average

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

a. The operation involved in withdrawing money from your bank account.

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

WHILE Population < Limit


Compute Population as Population + Births - Deaths

ENDWHILE

Example

WHILE employee.type NOT EQUAL manager AND personCount < numEmployees


INCREMENT personCount
CALL employeeList.getPerson with personCount RETURNING employee

ENDWHILE
More Examples (Cont.)

A number x raised to the power n is written as xn . Example if x = 2 and n = 3, we have 23 =


2*2*2 = 8.

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

Write a recursive algorithm 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
Suggested Solution Output: result, x raised to the
power of n
BEGIN
Enter the number x and the power n
IF n =0
RETURN 1
ELSE
RETURN x*Power(x,n-1)
END IF
END
CASE OTHERS
A CASE construct indicates a multiway branch based on conditions that are mutually exclusive. Four keywords, CASE, OF,
OTHERS, and ENDCASE, and conditions are used to indicate the various alternatives. The general form is:
CASE expression OF
condition 1 : sequence 1
condition 2 : sequence 2
...
condition n : sequence n
OTHERS:
default sequence
ENDCASE
The OTHERS clause with its default sequence is optional. Conditions are normally numbers or characters
indicating the value of "expression", but they can be English statements or some other notation that specifies the condition
under which the given sequence is to be performed. A certain sequence may be associated with more than one condition.
Example Example
CASE Title OF CASE grade OF
Mr : Print "Mister" A : points = 4
Mrs : Print "Missus" B : points = 3
Miss : Print "Miss" C : points = 2
Ms : Print "Mizz" D : points = 1
Dr : Print "Doctor" F : points = 0
ENDCASE ENDCASE
REPEAT-UNTIL

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

FOR each month of the year (good)


FOR month = 1 to 12 (ok)
FOR each employee in the list (good)
FOR empno = 1 to listsize (ok)
More Examples (Cont.)

In a class of 15 students, write an algorithm in pseudocode to calculate the:


a. Maximum grade
b. Minimum grade
Suggested Solutions

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

a. In a class of 15 students, write an algorithm in pseudocode to calculate the:


Average examination mark

b. How would the algorithm differ if the number of students is unknown?


Provide a modified algorithm to accommodate this change.
Suggested Solutions Unknown Students
Average examination mark AverageGrade
input: grades of n students
AverageGrade Output: the average grade
input: grades and number of students (n) BEGIN
Output: the average grade hasInput = TRUE
BEGIN i = 0
Enter number of students n sum =0
FOR i = 0 To n - 1 grade =[]
Enter grade[i] WHILE (hasInput)
END FOR Enter grade[i]
sum = 0 sum = sum + grade[i]
FOR i = 0 To n - 1 i=i+1
sum = sum + grade[i] Enter moreGrades? (Yes/No)
END FOR IF moreGrades = No THEN
RETURN sum / n hasInput = FALSE
END END IF
END WHILE
RETURN sum/i
END
NESTED CONSTRUCTS
The constructs can be embedded within each other, and this is made clear by use of indenting. Nested constructs should
be clearly indented from their surrounding constructs.
Example
SET total to zero
REPEAT
READ Temperature
IF Temperature > Freezing THEN
INCREMENT total
END IF
UNTIL Temperature < zero
Print total
In the above example, the IF construct is nested within the REPEAT construct, and therefore is indented.
Sample Pseudocode

"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

• What is Pseudo Code

• Common Pseudo Code Statements

You might also like