You are on page 1of 18

Computer Science (2210) Nadia Ahmad Shah

ALGORITHM DESIGN AND PROBLEM SOLVING:


Structure Diagrams Examples:

Flowchart Examples:
1. The flowchart shows an algorithm that should allow 60 test results to be entered into
the variable Score. Each test result is checked to see if it is 50 or more. If it is, the test
result is assigned to the Pass array. Otherwise, it is assigned to the Fail array.
(a) Complete this flowchart:

1
Computer Science (2210) Nadia Ahmad Shah

(b) Write a pseudocode routine that will check that each test result entered into the
algorithm is between 0 and 100 inclusive.

● Solution Using While...EndWhile Loop

WHILE Score < 0 OR Score > 100 (DO)


OUTPUT "Your entry must be between 0 and 100, inclusive, please
try again "
INPUT Score
ENDWHILE

● Solution using Repeat...Until Loop


REPEAT

2
Computer Science (2210) Nadia Ahmad Shah

IF Score < 0 OR Score > 100


THEN
OUTPUT "Your entry must be between 0 and 100, inclusive,
please try again "
INPUT Score
ENDIF
UNTIL Score >= 0 AND Score <= 100

2. The pseudocode represents an algorithm.


The pre-defined function DIV gives the value of the result of integer division. For
example, Y = 9 DIV 4 gives the value Y = 2.

The pre-defined function MOD gives the value of the remainder of integer division. For
example, R = 9 MOD 4 gives the value R = 1.

First ← 0
Last ← 0
INPUT Limit
FOR Counter ← 1 TO Limit
INPUT Value
IF Value >= 100
THEN
IF Value < 1000
THEN First ← Value DIV 100
Last ← Value MOD 10
IF First = Last
THEN
OUTPUT Value
ENDIF
ENDIF
ENDIF
NEXT Counter

3
Computer Science (2210) Nadia Ahmad Shah

3. The flowchart inputs the size of a number of car engines; a value of –1 stops the input.
This information is output: average engine size and number of engines with size > 1.5.

4
Computer Science (2210) Nadia Ahmad Shah

Standard Methods
1. Linear Search
The linear search is a standard algorithm used to find elements in an unordered list. The list is
searched sequentially and systematically from the start to the end one element at a time,
comparing each element to the value being searched for
If the value is found the algorithm outputs where it was found in the list
If the value is not found it outputs a message stating it is not in the list.

Example:
An example of using a linear search would be looking for a specific student name in a list or
searching for a supermarket item in a shopping list
OUTPUT “Enter a value to find”
INPUT Number
Found ← FALSE
Index ←1
REPEAT
IF Number = MyList [Index]
THEN
Found ← TRUE
ELSE

5
Computer Science (2210) Nadia Ahmad Shah

Counter ← Counter + 1
ENDIF
UNTIL Found =TRUE OR Counter > LENGTH(MyList)
IF Found = TRUE
THEN
OUTPUT Number, “found at position “, Counter
ELSE
OUTPUT Number, “ not found”
ENDIF
2. Bubble Sort
Bubble sort sorts items into order, smallest to largest, by comparing pairs of elements and
swapping them if they are out of order
The first element is compared to the second, the second to the third, the third to the fourth and
so on, until the second to last is compared to the last. Swaps occur if each comparison is out of
order. This overall process is called a pass
Once the end of the list has been reached, the value at the top of the list is now in order and
the sort resets back to the start of the list. The next largest value is then sorted to the top of the
list
More passes are completed until all elements are in the correct order
A final pass checks all elements and if no swaps are made then the sort is complete.

6
Computer Science (2210) Nadia Ahmad Shah

Example:
An example of using a bubble sort would be sorting into alphabetical order an array of names,
or sorting an array of student marks from a test.
MyList ← [5, 9, 4, 2, 6, 7, 1, 2, 4, 3]
FirstElement ← 1
LastElement ← LENGTH(MyList)
REPEAT
Swap ← FALSE
For Index ← FirstElement TO LastElement – 1
IF MyList[Index] > MyList[Index + 1]
THEN
Temp ← MyList[Index]
MyList[Index] ← MyList[Index + 1]

7
Computer Science (2210) Nadia Ahmad Shah

MyList[Index + 1] ← Temp
Swap ← TRUE
ENDIF
NEXT Index
LastElement ← LastElement – 1
UNTIL Swap = FALSE OR LastElement = 1
OUTPUT “Your sorted list is:”, MyList
3. Totalling
Totalling involves keeping a running total of values entered into the algorithm. An example may
be totalling a receipt for purchases made at a shop
The Total below starts at 0 and adds up the user inputted value for each item in the list. For
example, if the user has a receipt for four items: an apple (£0.50), a drink (£1), a sandwich (£2)
and a bar of chocolate (£1). The algorithm will total the cost for each item one at a time. The
output Total will be 4.50
Total ← 0
FOR Count ← 1 TO ReceiptLength
INPUT ItemValue
Total ← Total + itemValue
NEXT Count
OUTPUT Total
4. Counting
Counting works similarly to totalling except the count is incremented or decremented by a fixed
value, usually 1, each time it iterates. Counting keeps track of the number of times an action has
been performed. Many algorithms use counting, including the linear search and binary search
to track which element is currently being considered

▪ The count is incremented and each pass number is output until fifty outputs have been
produced
Count ← 0
DO
OUTPUT “Pass number”, Count

8
Computer Science (2210) Nadia Ahmad Shah

Count ← Count + 1
UNTIL Count >= 50

▪ The count is decremented from fifty until the count reaches zero. An output is produced
for each pass
Count ← 50
DO
OUTPUT “Pass number”, Count
Count ← Count – 1
UNTIL Count <= 0
5. Maximum, Minimum & Average
Finding the largest and smallest values in a list is a frequently used method in algorithms.
Examples could include the maximum and minimum student grades or scores in a game
Max ← Score[1]
Min ← Score[1]
FOR Count ← 2 TO ScoreSize
IF ScoreSize[Count] > Max
THEN
Max ← ScoreSize[Count]
ENDIF
IF ScoreSize[Count] < Min
THEN
Min ← ScoreSize[Count]
ENDIF
NEXT Count

▪ In the above algorithm, the initial max and min are set to the first value in the list and
the for loop starts at the second element instead of the first as the first value is the
benchmark to compare all other items to

9
Computer Science (2210) Nadia Ahmad Shah

▪ If no value is larger than the initial max, then Max doesn’t change. If no value is smaller
than the initial min, then Min doesn’t change
▪ The algorithm loops over each element asking whether the current value is larger than
Max and whether it is smaller than Min. Max and Min adjust their values throughout the
program depending on these conditions
▪ The program will eventually output the smallest and largest value in Min and Max
respectively
▪ Average values (also known as the mean) involve totalling all the list values and then
dividing by the number of values in the list
Total ← 0
FOR Count ← 1 TO ScoreSize
Total ← Total + ScoreSize[Count]
NEXT Count
Average ← Total / ScoreSize
Validation

● Validation and verification are used to ensure input data is correct, reasonable and
accurate
● Validation generally is about making sure data follows a set of specified rules created by
the programmer. Verification is about double-checking input data to make sure it's what
the user intended to enter

Validation

● Validation is the method of checking input data so that it is of an expected value and
therefore accepted by the system
● Programmers create rules using code that automatically checks user input data to make
sure the data is reasonable. If it is not reasonable then the data is rejected, usually with
a message explaining why it was rejected and allowing the user to reenter the data
● The different types of validation rules or checks are as follows:
o Range checks
o Length checks
o Type checks
o Presence checks

10
Computer Science (2210) Nadia Ahmad Shah

o Format checks
o Check digits

● Each piece of data may require multiple different checks to be fully valid.

1. Range check

● Range checks make sure the input data is a value between a user-defined minimum and
maximum value, for example, a percentage being between 0 and 100 inclusive or a date
in April is between 1 and 30 inclusive.

OUTPUT “Enter a number between 0 and 100”

REPEAT

INPUT Number

IF Number < 0 OR Number > 100

THEN

OUTPUT “Number is not between 0 and 100, please try


again”

ENDIF

UNTIL Number >= 0 AND Number <= 100

2. Length check

● Length checks check either that the input data is of an exact number of characters or in a
user specified number range of characters
● A bank 4-digit PIN number may be an example of an exact number of characters. If it is
not 4 digits in length it should be rejected

OUTPUT “Please enter your 4 digit bank PIN number”

REPEAT

INPUT Pin

11
Computer Science (2210) Nadia Ahmad Shah

IF LENGTH(Pin) <> 4

THEN

OUTPUT “Your pin number must be four characters in


length, please try again”

ENDIF

UNTIL LENGTH(Pin) = 4

● Passwords usually have a specified range, for example, eight to twenty characters in
length. If it does not fall within this range, it should be rejected

OUTPUT “Please enter a password between 8 and 20 characters”

REPEAT

INPUT Password

IF LENGTH(Password) < 8 OR LENGTH(Password) > 20

THEN

OUTPUT “Your password must be between 8 and 20


characters in length, please
try again”

ENDIF

UNTIL LENGTH(Password) >= 8 AND LENGTH(Password) <= 20

3. Type checks

● Type checks make sure the input data is of the correct data type. For example,
someone's age should be an integer (a whole number) whereas their name should be a
string (a bunch of characters)

OUTPUT “Enter an integer number”

REPEAT

12
Computer Science (2210) Nadia Ahmad Shah

INPUT Number

IF Number <> DIV(Number, 1)

THEN

OUTPUT “Not a whole number, please try again”

ENDIF

UNTIL Number = DIV(Number , 1)

4. Presence check

● Presence checks make sure that input data has been entered and that the input box has
not been left empty
● A login system requires presence checks as both a username and password are required
for authentication

OUTPUT “Enter your username”

REPEAT

INPUT Username

IF Username = “”

THEN

OUTPUT “No username entered, please try again”

ENDIF

UNTIL Username <> “”

5. Format check

● Format checks make sure that input data is of a predefined pattern


● Identification codes e.g. AP1234 and dates are examples of patterns
● Format checks are done using pattern matching and string handling
● The algorithm below checks a six digit identification number against the format “XX9999”
where X is an uppercase alphabetical letter and 9999 is a four digit number

13
Computer Science (2210) Nadia Ahmad Shah

● The first two characters are checked against a list of approved characters. The first character
is compared one at a time to each valid character in the ValidChars array. If it finds a match
it stops looping and sets ValidChar to True. The second character is then compared one at a
time to each valid character in the ValidChars array. If it finds a match then it also stops
looping and sets ValidChar to True
● Casting is used on the digits to turn the digit characters into numbers. Once the digits are
considered a proper integer they can be checked to see if they are in the appropriate range
of 0-9999
● If any of these checks fail then an appropriate message is output

INPUT IDNumber

IF LENGTH(IDNumber) <> 6

THEN

OUTPUT “ID number must be 6 characters long”

END IF

ValidChars ← “ABCDEFGHIJKLMNOPQRSTUVWXYZ”

FirstChar ← SUBSTRING(IDNumber, 1, 1)

ValidChar ← False

Index ← 1

WHILE Index <= LENGTH(ValidChars) AND ValidChar = False DO

IF FirstChar = ValidChars[Index]

THEN

ValidChar ← True

ENDIF

Index ← Index + 1

ENDWHILE

14
Computer Science (2210) Nadia Ahmad Shah

IF ValidChar = False

THEN

OUTPUT “First character is not a valid uppercase


alphabetical character”

ENDIF

SecondChar ← SUBSTRING(IDNumber, 2, 2)

ValidChar ← False

Index ← 1

WHILE Index <= LENGTH(ValidChars) AND ValidChar = False DO

IF SecondChar = ValidChars[Index]

THEN

ValidChar ← True

ENDIF

Index ← Index + 1

ENDWHILE

IF ValidChar = False

THEN

OUTPUT “Second character is not a valid uppercase


alphabetical character”

ENDIF

Digits ← INT(SUBSTRING(IDNumber, 3, 6))

IF Digits < 0000 OR Digits > 9999

15
Computer Science (2210) Nadia Ahmad Shah

THEN

OUTPUT “Digits invalid. Enter four valid digits in the range


0000-9999”

ENDIF

6. Check digits

● Check digits are numerical values that are the final digit of a larger code such as a
barcode or an International Standard Book Number (ISBN). They are calculated by
applying an algorithm to the code and are then attached to the overall code
● Check digits help to identify errors in data entry such as mistyping, mis-scanning or
misspeaking
o Such errors include missing or additional digits, swapped digits, mispronunciation
of digits or simply an incorrect digit

Barcode ← “9780201379624”

Total ← 0

FOR Index = 1 to LENGTH(Barcode) - 1

IF Index MOD 2 = 0

THEN

Total ← Total + CAST_TO_INT(Barcode[Index])*3

ELSE

Total ← Total + CAST_TO_INT(Barcode[Index])*1

ENDIF

NEXT Index

CheckDigit ← 10 - Total MOD 10

IF CheckDigit = Barcode[LENGTH(Barcode)]

16
Computer Science (2210) Nadia Ahmad Shah

THEN

OUTPUT “Valid check digit”

ELSE

OUTPUT “Invalid check digit”

ENDIF

Verification

● Verification is the act of checking data is accurate when entered into a system
● Mistakes such as creating a new account and entering a password incorrectly mean
being locked out of the account immediately
● Verification methods include: double entry checking and visual checks

Double entry checking

● Double entry checking involves entering the data twice in separate input boxes and then
comparing the data to ensure they both match. If they do not, an error message is
shown

REPEAT

OUTPUT “Enter your password”

INPUT Password

OUTPUT “Please confirm your password”

INPUT ConfirmPassword

IF Password <> ConfirmPassword

THEN

OUTPUT “Passwords do not match, please try again”

ENDIF

17
Computer Science (2210) Nadia Ahmad Shah

UNTIL Password = ConfirmPassword

Visual check

● Visual checks involve the user visually checking the data on the screen. A popup or
message then asks if the data is correct before proceeding. If it isn’t the user then enters
the data again

REPEAT

OUTPUT “Enter your name”

INPUT Name

OUTPUT “Your name is: “, Name, “. Is this correct? (y/n)”

INPUT Answer

UNTIL Answer = “y”

18

You might also like