COMPUTER SCIENCE - 2210
Paper 2
1 Boolean Logic
2 Databases
3 Algorithm design and problem-solving
1 Boolean Logic
Writing Algorithms
❖ Use Indentation – Blocks of statements are indented to increase readability
❖ Case - Keywords are in upper case, e.g. IF, REPEAT, PROCEDURE
Identifiers are in mixed case with upper case letters indicating the beginning of new words, e.g. NumberOfPlayers
❖ Comments are preceded by two forward slashes //.It is vital to write comments to gain A03 marks
❖ Variables, constants and data types
➢ Integer written as normal in the denary system, e.g. 5, –3
➢ Real always written with at least one digit on either side of the decimal point, zeros being added if necessary, e.g. 4.7, 0.3, –4.0, 0.0
➢ Char a single character delimited by single quotes, e.g. ꞌxꞌ, ꞌcꞌ, ꞌ@ꞌ
➢ String delimited by double quotes. A string may contain no characters (i.e. the empty string), e.g. "This is a string", ""
➢ Boolean TRUE, FALSE
❖ Identifiers - (the names given to variables, constants, procedures and functions)
➢ Written in mixed case e.g. FirstName.
➢ Can only contain letters (A–Z, a–z) and digits (0–9).
➢ Must start with a capital letter
➢ Accented letters and other characters, including the underscore, should not be used.
Variables
Declaring Variables
Arrays
DECLARE <identifier> : <data type>
Declaring arrays
Example –
DECLARE <identifier> : ARRAY[<l>:<u>] OF <data type>
DECLARE Counter : INTEGER
DECLARE <identifier> : ARRAY[<l1>:<u1>, <l2>:<u2>] OF <data type>
DECLARE TotalToPay : REAL
Example –
DECLARE GameOver : BOOLEAN
DECLARE StudentNames : ARRAY[1:30] OF STRING
Constants DECLARE NoughtsAndCrosses : ARRAY[1:3, 1:3] OF CHAR
Declaring Constants Using arrays
CONSTANT <identifier> ← <value> Example –
Example – StudentNames[1] ← "Ali"
CONSTANT HourlyRate ← 6.50 NoughtsAndCrosses[2,3] ← ꞌXꞌ
CONSTANT DefaultText ← "N/A“
Assignments
The assignment operator is ←
<identifier> ← <value>
Example –
Counter ← 0
Counter ← Counter + 1
TotalToPay ← NumberOfHours * HourlyRate
Common operations The integer division
Input and output DIV(<identifier1>, <identifier2>)
INPUT <identifier> Returns the quotient
OUTPUT <value(s)> MOD(<identifier1>, <identifier2>)
Examples – Examples –
DIV(10, 3) returns 3
INPUT Answer
MOD(10, 3) returns 1
INPUT “Enter Answer”, Answer
OUTPUT Score
Logical operators
= equal to
OUTPUT "You have ", Lives, " lives left“
< less than
Arithmetic operations <= less than or equal to
+ addition > greater than
– subtraction >= greater than or equal to
* multiplication <> not equal to
/ division Boolean operators
^ raised to the power of AND, OR and NOT
Examples - Examples –
Answer ← Score * 100 / MaxMark IF (Answer < 0) OR (Answer > 100) THEN
Answer ← Pi * Radius ^ 2 Correct ← FALSE
ELSE
Correct ← TRUE
ENDIF
String operations
LENGTH(<identifier>) - Returns the length of string.
LCASE(<identifier>) - Returns the characters in lower case
UCASE(<identifier>) - Returns the characters in upper case
SUBSTRING(<identifier>, <start>, <length>) - Returns a string of length starting at position start
Example –
LENGTH("Happy Days") will return 10
LCASE(ꞌWꞌ) will return ꞌwꞌ
UCASE("Happy") will return "HAPPY"
SUBSTRING("Happy Days", 1, 5) will return "Happy“
Other library routines
ROUND(<identifier>, <places>) - Returns rounded to places number of decimal places
RANDOM() - Returns a random number between 0 and 1 inclusive.
Example –
Value ← ROUND (RANDOM() * 6, 0) // returns a whole number between 0 and 6
IF statements Selection
IF <condition> THEN
<statements> CASE statements
ENDIF CASE OF <identifier>
IF statements with an ELSE clause <value 1> : <statement>
IF <condition> THEN <value 2> : <statement>
<statements> ...
ELSE OTHERWISE <statement>
<statements> ENDCASE
ENDIF Example –
Example – INPUT Move
IF ChallengerScore > ChampionScore THEN CASE OF Move
IF ChallengerScore > HighestScore THEN ꞌWꞌ : Position ← Position – 10
OUTPUT ChallengerName, " is champion and highest scorer"
ꞌEꞌ : Position ← Position + 10
ELSE
ꞌAꞌ : Position ← Position – 1
OUTPUT Player1Name, " is the new champion"
ꞌDꞌ : Position ← Position + 1
ENDIF
ELSE
OTHERWISE OUTPUT "Beep"
OUTPUT ChampionName, " is still the champion" ENDCASE
IF ChampionScore > HighestScore THEN
OUTPUT ChampionName, " is also the highest scorer"
ENDIF
ENDIF
Post-condition (REPEAT) loops
Iteration
Count-controlled (FOR) loops REPEAT
<Statements>
FOR <identifier> ← <value1> TO <value2>
UNTIL <condition>
<statements>
The condition is evaluated after the statements are executed. If it
NEXT <identifier>
evaluates to TRUE the loop terminates.
Example –
Example –
Total ← 0
REPEAT
FOR Row ← 1 TO MaxRow
OUTPUT "Please enter the password"
RowTotal ← 0
INPUT Password
FOR Column ← 1 TO 10
UNTIL Password = "Secret"
RowTotal ← RowTotal + Amount[Row, Column]
NEXT Column Pre-condition (WHILE) loops
OUTPUT "Total for Row ", Row, " is ", RowTotal WHILE <condition> DO
Total ← Total + RowTotal <statements>
NEXT Row ENDWHILE
OUTPUT "The grand total is ", Total The condition is evaluated before the statements are executed. If it evaluates to FALSE the loop
terminates.
Example –
WHILE Number > 9 DO
Number ← Number – 9
ENDWHILE
Procedures and functions
Defining and calling procedures
PROCEDURE <identifier>
<statements>
ENDPROCEDURE
A procedure with parameters
PROCEDURE <identifier>(<param1>:<datatype>, <param2>:<datatype>...)
<statements>
ENDPROCEDURE
Procedures should be called as follows:
CALL <identifier>
Defining and calling functions
CALL <identifier>(Value1,Value2...)
FUNCTION <identifier> RETURNS <data type>
Example – <statements>
PROCEDURE DefaultLine ENDFUNCTION
CALL LINE(60) A function with parameters
ENDPROCEDURE FUNCTION <identifier>(<param1>:<datatype>, <param2>:<datatype>...) RETURNS <data type>
<statements>
PROCEDURE Line(Size : INTEGER) ENDFUNCTION
DECLARE Length : INTEGER
FOR Length ← 1 TO Size Example –
OUTPUT '-'
NEXT Length FUNCTION SumSquare(Number1:INTEGER, Number2:INTEGER) RETURNS INTEGER
ENDPROCEDURE RETURN Number1 * Number1 + Number2 * Number2
ENDFUNCTION
IF MySize = Default THEN
CALL DefaultLine OUTPUT "Sum of squares = ", SumSquare(10, 20)
ELSE
CALL Line(MySize)
ENDIF
File handling
Open a File
OPENFILE <File identifier> FOR <File mode>
The following file modes are used:
❖ READ - data to be read from the file
❖ WRITE - data to be written to the file. A new file will be created and any existing data in the file will be lost
❖ APPEND – data to be added to an existing file
Read Date from a File
READFILE <File Identifier>, <Variable>
Write Data to a File
WRITEFILE <File identifier>, <Variable>
Closing a File
CLOSEFILE <File identifier>
Example – to copy a line of text from FileA.txt to FileB.txt
DECLARE LineOfText : STRING
OPENFILE FileA.txt FOR READ
OPENFILE FileB.txt FOR WRITE
READFILE FileA.txt, LineOfText
WRITEFILE FileB.txt, LineOfText
CLOSEFILE FileA.txt
CLOSEFILE FileB.txt
Draw the arrays, this will help to understand the scenario
Make a structure using Comments
// Initialize arrays
// Initialize forfor
arrays lunch items
lunch andand
items prices
prices
LunchItems[1] "Sandwich"
LunchItems[1] "Sandwich"
LunchItems[2] "Salad"
LunchItems[2] "Salad"
LunchItems[3] "Pizza"
LunchItems[3] "Pizza"
LunchPrices[1] 4.99
LunchPrices[1] 4.99
LunchPrices[2] 5.49
LunchPrices[2] 5.49
LunchPrices[3] 6.99
LunchPrices[3] 6.99
// Input a new student's name and lunch order details and Validate
// Input Student Name and validate
INPUT "Enter student's name:", StudentName
WHILE StudentName = “” DO
INPUT "Student Name cannot be a space. Enter a name:", StudentName
END WHILE
// Input lunch Item and validate
INPUT "Enter lunch item choice (1 for Sandwich, 2 for Salad, 3 for Pizza):", item
WHILE (item < 1) OR (item > 3) DO
INPUT “Invalid item Choice. Enter a valid lunch item”, item
END WHILE
// Input Quantity of lunch Item and validate
INPUT “Enter quantity of " + LunchItems[item] , quantity
WHILE quantity < = 0 DO
OUTPUT "Quantity must be greater than 0. Please enter a valid quantity.", quantity
END WHILE
// Calculate total cost of lunch order
TotalCost = LunchPrices[item] * quantity
//Store in Student & LunchOrders array
Student[index] StudentName
LunchOrders[index, 1] LunchItems[item]
LunchOrders[index, 2] quantity
LunchOrders[index, 3] LunchPrices[item]
LunchOrders[index,4] TotalCost
//Output Lunch Order details
OUTPUT "Lunch order for " , Student[index]
OUTPUT "Item: " , LunchOrders[index, 1]
OUTPUT "Quantity: " , LunchOrders[index, 2]
OUTPUT "Total cost: $" , LunchOrders[index,4]
//Continue with the next order
NEXT index