0 ratings0% found this document useful (0 votes) 32 views18 pagesComputer Science IGCSE Revision Guide Part 2
COMPUTER SCIENCE IGCSE FULL REVISION GUIDE FOR PAPER 2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
CAIE IGCSE
for Frank for personal use onya a ees
1, Algorithm Design &
Problem-Sol
9
1.2. Program Development Life Cycle
(PDLC)
Analysis
Design
Coding
Testing
Maintenance
Analysis
+ Before solving a problem, itis essential to define and
document the problem clearly, known as the
“requirements specification" for the program.
‘+ The analysis stage involves using tools lke abstraction
‘and decomposition to identi the specific requirements
forthe program
‘Abstraction focuses on the essential elements needed
forthe solution while eliminating unnecessary details
and information,
‘+ Decomposition involves breaking down complex
problems into smaller, more manageable parts that can
be soled individually
‘+ Daly tasks can be decomposed into constituent parts for
easier understanding and solving,
Design
‘+ The program specification derived from the analysis,
stage is used 2s a guide for program development,
‘+ During the design stage, the programmer should clearly
Understand the tasks to be completed, the methods for
performing each task, and how the tasks will work
together.
‘+ Documentation methods such as structure charts,
flowcharts, and pseudocode can be used to document
the program's design formally,
Coding and iterative testing
‘+The program or set of programs is developed based on
the design,
+ Each module of the program is written using a suitable
programming language.
+ Testing! conducted to ensure that each module
functions correctly,
+ Iterative testing is performed, which involves conducting,
‘modular tests, making code amendments if necessary,
and repeating tests untilthe module meets the required
functionality.
Testing
‘+ The completed program or set of programs is executed
‘multiple times using various test data sets.
+ This esting process ensures that all the tasks within the
program work together as specified in the program
design.
‘+ Running the program with different test data can identify
and address potential issues and errors.
‘+ The testing phase aims to verify the overall functionality
and performance of the program by evaluating its
behaviour with various inputs
1.2, Structure Diagrams
+ Every computer system is made up of sub-systems,
which are in turn made up of further sub-systems.
‘Structure Diagrams - The breaking down of a computer
system into sub-systems, then breaking each sub-system
Into smaller sub-systems until each one only performs a
single action. A structure diagram diagrammatically
represents a top-down design. Example below.
em ea
1.3. Pseudocode & Flowcharts
WWW.ZNOTES.ORGa a ees
‘+ Pseudocode - Verbal representation of an algorithm (2
process or set of steps) and flowcharts are 2
diagrammatic representation,
‘+ Flowcharts: A flowchart shows diagrammatically the
steps required to complete a task and the order that
they are to be performed
‘+ Algorithm: These steps, together with the order, are
called an algorithm
‘An example of a flowchart is given below from a past paper
question in which all ofthe functions of a fowchart are
shown:
‘This flowchart’ task isto check ifa rider's height is more the
requirernent (1.2)in this case. It then counts untilthe
accepted riders are 8, After they are 8, it outputs the
umber of rejected riders and tell the rest chat they are
ready to go!
2. Pseudocode
WWW.ZNOTES.ORG
+ Declaration & Usage of Variables & Constants
‘Variable - Store of data which changes during
‘execution ofthe program (due to user input)
+ Constant ~ Store of data that remains the same
during the execution of the program
+ Basic Data Types
‘Integer - Whole Number e.g. 2:8; 100,
+ Real - Decimal Number e.g, 7.00; 5.64
+ Char~ Single Character ea"
‘+ String - Multiple Characters (Text) eg. "2Notes':
“cool”
‘+ Boolean - Only 2 Values eg, True/False; Yes/No; 0/1
‘+ Input & Output (READ & PRINT) - Used to receive and
display data to the user respectively, ts recommended
10 use input and output commands}
{INPUT Nane
OUTPUT “Hello Hr." , Nane
1] Riternatively //
READ Nane
PRINT “Hello Hr,” Kame
+ Declaration of variable - A variable/constant can be
declared by the following manner
DECLARE [Variable Nace] : [DATATYPE OF VARIABLE]
+ Array: Aray is similar to variable but it can store
‘multiple values of same datatype under single name
DECLARE [ARRAYMAME] : ARRAY (Lower Limit : Upper Lin
‘+ Assignment Each variable is assigned using a left
[VARIABLE NAME] <---- [Value to be assigned]
ArrayNane [IndexValue] <---- [Value to be assigned]
*+ Conditional statements:
IF. THEN. .ELSE..ENDIF
‘sctuelargeata seer oy Pant anstasesl or aea a ees
IF [CONDITION] THEN
[CONSEQUENCE]
ELSE
[CONSEQUENCE]
ENDIF
IF GRADE > 100 THEN
OUTPUT “INVALID”
ELSE
OUTPUT “VALID”
ENDIF
CCASE..OF..OTHERWISE,,.ENDCASE ~ Multiple conditions and
corresponding consequences \n
CASE OF [VARIABLE]
OPTION: [CONSEQUENCE:
OTHERWISE: [CONSEQUENCE]
ENDCASE
CASE OF GRADE
GRADE>80: OUTPUT “A”
GRADE>70: OUTPUT “B”
GRADE>60: OUTPUT “C”
OTHERWISE: OUTPUT “FAIL”
ENDCASE
+ Loop Structures:
FORWTO.NEXT : WiLL run for a determined/known
FOR [VARIABLE] € [VALUE] TO [VALUE
[cone]
NEXT
REPEAT... UNTIL Will run at least once till condition is
satisfied; Verification is done after running code
REPEAT
[coDE]
UNTIL [CONDITION]
WHILE,.00.,.ENDWHILE - May not ever run; Verification
is done before running code
WHILE [CONDITION] DO
[cong]
ENDWHILE
Note: When using conditions in these loop structures
‘and conditional statement, it has to be kept in mind that
itcan be done in two ways.
1 use of a Boolean variable that can have the value
TRUE or FALSE
2, comparisons made by using coparison operators,
where comparisons are made from left to right
TF [BOOLEAN VARIABLE]
THEN
‘OUTCOME
eLse
ourcome
e01F
TF ((CONDITION 1) OR ( CONDITION 2)) AND (CONDITION
THEN
‘ourcoue
ELSE
‘uTcoMe
ENOTF
‘schtuelargeata sc roy Pant anstasersl or aa a ees
. | Greater than
Less than
qual
Greater than or equal
[Les tan or equa
= Not equal
ax ‘Both
[on ‘Either
(nor Not
2.2. Standard methods used in
algorithm:
+ Totalling Totaling means keeping a total that values are
added to
Total « @
FOR Counter * 1 TO LoopLisit
Total + Total + ValueToberotalied
NExT Counter
‘+ Counting: Keeping 2 count of the number of times an.
action is performed is another standard methed.
Passcount + @
FoR Counter « 1 TO LoopLinit
INPUT Value
IF value > Range
THe
PassCount © PassCount + 2
ENDIF
NEXT Counter
“+ Maximum, minimum and average : Finding the largest
{and smallest values in a lst are two standard methods
that are frequently found in algorithms
WWW.ZNOTES.ORG
Naxiumunalue <--- Array[1] Minimunvalue <--- Arrayl
FOR Counter « 2 TO LoopLimit
IF Array[Counter] > Maximusvalue
THEN
Waximunvalue « Acray[Counter]
eN0rF
IF array[Counter] < minimunvalue
en
Minimunvalue « Array[Counter]
eNoIF
NeXT Counter
1 werage//
Total + @
FOR Counter + 1 TO Nunberofvalues
Total + Total + StudentMark{Counter]
Next counter
Average + Total / NusberofValues
+ Linear Search: Ina linear search, each item in the list is
inspected sequentially untl a match is found or che
entire lists traversed
INPUT Value
Found + FALSE
counter « @
REPEAT
IF Value = Array{Counter]
wen
Found © TRUE
ese
Counter © Counter + 1
e0rF
UNTIL Found OR Counter > Nunberofvalues
IF Found
THEN
OUTPUT Value , * found at position " , Counter,
ease
OUTPUT Value , " not found.’
ENDIF
‘sctuelargeata seer oy Pant anstasesl or aea a ees
‘+ Bubble Sort: iteratively compare and swap adjacent,
elements in a ist to sort them, Start from the frst,
clement and continue until the second-toast element,
After each pass, the last element isin its correct place,
However, other elements may stl be unsorted. Repeat
the process, excluding the last element, until only one.
element remains or no swaps are needed.
First ©
Last «18
‘Swap + FALSE
FOR Index « First TO Last - 2
IF Arcay[Index] > Array[Index + 1)
Temp + Arcayl Index]
Array[Index} « Array(Index + 2)
ArcaylIndex + 1] « Tesp
Swap © TRUE
NeXT Index
Last © Last = 2
UNTIL (NOT Swap) OR Last = 2
2.3. Validation and Verification
‘To ensure the acceptance of reasonable and accurate data
Inputs, computer systems must thoroughly examine each
data item before accepting it, and this is where Validation
and Verification come into play!
Validation
Validation in computer systems involves automated checks
to ensure the reasonableness of data before accepting it. IF
the data is invalid, the system should provide an explanatory
‘message for rejection and allow another chance to enter the
data,
‘There are multiple types of validation. These include:
Range check
‘Arange check verifies that 2 numerical value falls within
specified upper and lower limits
WWW.ZNOTES.ORG
REPEAT
INPUT Value
IF Value < Mininunvalue OR Value > Maximunvalue
OUTPUT “The student's mark should be in the range’
ENoTF
UNTIL Value >= Mininunvalue AND Value <= Maxinunvals,
Length check
This can elther ensure that data consists ofa precise
‘number of characters
OUTPUT "Please enter your value of ", Limit," che
REPEAT
INPUT Value
TF LENGTH(Value) <> Limit
THEN
OUTPUT "Your value must be exactly" , Linit ," che
eNoIF
UNTIL LENGTH(Value) = Lint
Tecan also checkifthe data entered is a reasonable number
of characters or not
OUTPUT “Please enter your value
REPEAT
INPUT Value
IF LENGTH(Value) > UpperLinit OR LENGTH(Value) < Le
THEN
OUTPUT “Too short or too long,
UNTIL LENGTH(Value)
ease re-enter
UpperLinit AND LENGTH(ValUe)
Type check
‘Atype check verifies thatthe entered data corresponds to a
specific data type.
ourPur “Enter the value *
REPEAT
INPUT Value
IF Value © orv(value, 1)
THEN
OUTPUT “This must be a whole uber, please re-er
UNTIL Value = pIVv(value, 2)
Presence check
[A presence check checks to ensure that some data has been
fentered and the value has not been left blanka a ees
OUTPUT “Please enter the value
REPEAT
INPUT Value
IF value =
THEN
OUTPUT “*-Required
ENDIF
UNTIL Value «>
Format Check
‘Aformat check checks that the characters entered conform
to a pre-defined pattern,
Check Digit
‘+ Acheck digi is the final digit Included in a code; tis
calculated from all the other digits.
+ Check digits are used for barcodes, product codes,
International Standard Book Numbers (ISBN), and
Vehicle Identification Numbers (VIN)
Verification
Verification is checking that data has been accurately copied
from one source to another
‘There are 2 methods to verify data during entry (there
are other methods during data transfer, but they are in
paper 1)
2. Double Entry
‘+ Datais inputted twice, potentially by different operators.
‘+ The computer system compares both entries and if they
differ, an error message is displayed, prompting the data
to be reentered,
2. Screen/Visual check
‘+ Ascreen/visual check involves the user manually
reviewing the entered data
‘+ After data entry, the system displays the data on the
screen and prompts the user to confirm is accuracy
before proceeding
‘+The user can compare the displayed data against a paper
document used as an input form or rely on thelr own,
knowledge to verity correctness,
3. Test Data
WWW.ZNOTES.ORG
+ Test data refers to input values used to evaluate and
assess the functionality and performance of a computer
program or system.
+ Ithelps identify errors and assess how the program
handles afferent scenarios
3.1. Normal Data
‘+ Normal data s the test data which accepts values in
acceptible range of values of the program
+ Normal data should be used to work through the
solution to find the actual result(s) and see if they are the
same as the expected result(s)
+ eg; in a program where only whole number values
ranging from 0 to 100 inclusive) are accepted, normal
test data willbe: 23, 54,64 ,2 and 100
3.2. Abnormal Data
+ Test data that would be rejected by the solution as not
suitable, ifthe solution is working properly is called
abnormal test data / erroneous test data,
+ eg, ina program where only whole number values
ranging from 0 to 100 (inclusive) are accepted, abnormal
data will be: -1, 151, 200, 67.2, “Sixty-Two" and -520
3.3, Extreme Data
‘Extreme data are the largest and smallest values that
normal data can take
+ eg, in @ program where only whale number values
ranging from 0 t0 100 (inclusive) are accepted, extreme
data will be: @ and 100
3.4. Boundary Data
+ Thisis used to establish where the largest and smallest
values occur
+ At each boundary two values are required: one value is
accepted and the other value is rejectes,
‘+ eg. ina program where only whole number values
ranging from 0 to 100 (inclusive) are accepted, one
example of boundary data will be: 100 and 101, 100 wil
be accepted and 101 will nt be accepted
4. Trace Tablea a ees
“+ Atrace table is utilized to document the outcomes of,
every step in an algorithm. tis employed to record the
variable's value each time it undergoes a change.
+ Adry run refers to the manual process of systematically
‘executing an algorithm by following each step in
sequence,
‘+ Atrace table is set up with a column for each variable
and a column for ary output eg.
a Bc |x | output
0 | 0 | 100
ps to
Test data is employed to execute a dry run of the flowchart
and document the outcomes ina trace table, Ouring the dry
‘+ Whenever avariable's value changes, the new value is
recorded in the respective column of the trace table.
‘+ Each time a value is outputted, its displayed in the
‘output column,
‘An example of trace table is given below using a past paper
question:
The flowchart below inputs the height of children who
‘ant to ride on a rollercoaster. Children under 1.2 metres
are rejected, The ride starts when eight children have been
accepted.
Complete the trace table for the input data: 141.3, 1.11.3,
10,15, 1.2, 13, 14,13, 09, 1.5, 1.6, 10
WWW.ZNOTES.ORG
a oorur
4.1. Identifying errors:
+ Trace tables can be used to trace errors in a program,
For example, ifthe requirement for the previous
question would be to accept riders that are of height 1.2
too, rather than rejecting them, then the error would
hhave been caught in the trace table as when 1.2 is
‘entered, it would increment rejected which it shouldn't in
our example
5. How to write an algorithm?
‘The ability to write an algorithm is very important for
this syllabus and paper. Some key steps/points to be
known in-order to write the perfect algorithm are as
follows:
‘sctuelargeata seer oy Pant anstasesl or aea a ees
Make sure that the problems clearly understood
Which includes knowing the purpose of tne algorithm
and the tasks to be completed by the algorithm,
2. Break the problem nto smaller problems (eg. ina
program which outputs average values, divide the
problem into muttiple ones Le. how to count the
umber of iterations and how to count the total ofall
values)
23. Identify the data that is needed to be saved into
variables/constants/arrays and what datatype it's
‘and declare all the variables/constants/arrays
accordingly, with meaningfull names
4, Decide on how you are going to construct your
algorithm, either using a flowchart or pseudocode. If
you are told how to construct your algorithm, then
follow the guidance
5, Construct your algorithm, making sure that itcan be
‘easily read and understood by someone else, Take
particular care with syntax e.g. when conditions are
used for loops and selection.
6, Use several sets of test data (Normal, Abnormal and
Boundary) to dry run your algorithm and check ifthe
‘expected results are achieved (a trace table can be
used for this purpose) . If errors found, find the
point of error inthe trace table and fix tin the code.
Note: The algorithms that you have looked at so farin these
notes were not designed with readability in mind because
you needed to work out what the problem being solved was
6, Programming
6.1, Programming Languages
‘There are many high-level programming languages to
choose from. We will only be treating Python, Visual
Basic, or Java,
WWW.ZNOTES.ORG
+ Python is an open-source, versatile programming
language that encourages quick program development
and emphasises code readability. The integrated
development environment (IDF) showeased in this
chapter i referred to as 1D
+ Visual Basic is a popular programming language that is
extensively used for Windows development. The
integrated development environment (IDF) featured in
this chapter is known as Visual Studio, which is utilsed
for capturing screenshot
+ Java is a widely adopted programming language vtlised
by numerous developers, The integrated development
environment (IDE) employed for capturing screenshots in
this chapter Is known as Blue)
6.2, Programming Concepts
Constructs of a Program
+ Data use - variables, constants and arrays
+ Sequence - order of steps ina task
+ Selection - choosing a path through a program
‘+ Iteration - repetition of a sequence of steps in a program
+ Operators use arithmetic for calculations and logic and
Boolean for decisions
Variables and Constants
‘+ Avariable within @ computer program refers toa named
storage unit with a value that can be modified
‘throughout the program's execution. To enhance
comprehension for others, itis advisable to assign
significant names to variables.
‘+ Aconstant within a computer program represents a
ramed storage unit that holds a value whieh remains
Unchanged throughout the program's execution. Similar
to variables, it is recommended to assign meaningful
names to constants to enhance comprehensibilty for
others
Data Typesa a ees
“Different datatypes are assigned to computer systems
for effective processing and storage
‘+ Data types allow data, such as numbers or characters, to
be stored appropriately
‘+ Data types enable effective manipulation using
‘mathematical operators for numbers and character
concatenation
+ Some data types provide automatic validation,
‘+ The types of datatypes are told in Chapter 1 already!
Input and Output
‘+ Programs require input and output statements to handle
data
‘+ INIGCSE Computer Science, algorithms and programs
are designed to take Input from a keyboard and output
toa screen
‘+ Prompting the user with clear instructions for input is
necessary forthe user to understand what is expected,
‘Input data in programming languages must match the
required data type of the variable where it willbe stored
‘+ By default, inputs are treated as strings, but commands
can convert input to integer or real number data types,
“+ Users should be provided with information about the
‘outputiresults for a program to be useful
+ Each output should be accompanied by 2 message
explaining the resul’s meaning or significance,
‘+ fan output statement has multiple parts, they can be
separated by a separator character.
6.3. Basic Concepts
When writing the steps required to solve @ problem, the
following concepts need to be used and understood:
+ Sequence
Selection
+ eration
+ Counting and totaling
+ String handling
+ Use of operators
Sequence
he ordering of the steps in an algorithm Is very important.
{An incorrect order can lead to incorrect resuks andlor extra
steps that are not required by the task
Selection
Selection isa very useful technique, allowing different routes
through the steps of a program. The code ofthis s explained
inthe notes of previous chapters.
Iteration
‘As explained in the previous chapter, we already
Totalling and Counting
{As explained in the previous chapter, we already
String Handling
‘Strings are used to store text and can contain various
characters.
‘+ An empty string has no characters, while the
programming language specifies the maximum number
of characters allowed,
+ Characters in a string can be identified by the'r position
umber, starting from either zero or one, depending on
the programming language.
+ String handling is an important aspect of programming,
*# InIGCSE Computer Science, you wil need to write
algorithms and programs forthe following string
methods:
‘+ Length: Determines the number of characters in a
string, including spaces.
‘+ Substring: Extracts 2 portion of a string,
“+ Upper: Converts all letters in a string to uppercase.
‘= Lower: Converts all letters in a string to lowercase,
‘+ These string manipulation methods are commonly
provided in programming languages through library
Finding the length ofa string:
LENGTH(*Text Here")
Lenemi(variabie)
Extracting a substring froma string:
SUBSTAING("Conputer Science”, 18, 7)
// returns the next 7 values’ starting fron the 10th
SUBSTRING(Vardable, Position, Length)
Converting string to upper case
UcASE(“Text here")
case (variable)
Converting a string to lowercase
WWW.ZNOTES.ORGa a ees
LCASE("Text Here")
Lease(Variable)
Arithm«
Logical and Boolean Operators
‘As explained in the previous chapter, we already
Use of Nested Statements
‘+ Selection and iteration statements can be nested,
‘meaning one statement can be placed inside another.
‘+ Nested statements help reduce code duplication and,
simplity testing of programs.
‘+ Different types of constructs can be nested within each
other, such as selection statements within condition-
controlled loops or loops within other loops.
Procedures and Functions
Procedures and functions are defined at the start of the
code
+ Aprocedure refers toa collection of programming
statements organized under a single name, invoked at
any glven point Ina program to execute a specific task
‘+ Afunction is a compilation of programming statements
consolidated under a singular name, invoked at any
‘moment within a program to accomplish a particular
task. Unlke a procedure, a function also has the
capability to return a value back tothe main program.
‘+ Parameters refer to variables that store the values of,
arguments passed to a procedure or function. While not
all procedures and functions require parameters, some
Ltiize them to facilitate their operations,
Procedures without parameters:
PROCEDURE ProcedureName ()
‘Conmands]
ENDPROCEDURE
1/CalLing/cunning the procedure
CALL ProcedureName()
‘The procedure with parameters:
PROCEDURE ProcedureNane (ParaneterNane : Parameter:
‘Conmands]
ENOPROCEOURE.
1/CalLing/cunning the procedure
CALL ProcedureNane (ParaneterValue)
Function:
FUNCTION FunctionNane (ParaneterNane : Paraneterbatz
[commanés]
RETURN ValueToBeReturned
+ When defining procedures and functions, the header is
the first statement in the definition.
+ The header includes:
‘+ The name of the procedure or function,
‘+ Parameters passed to the procedure or function,
along with their data types.
+ The datatype ofthe return value for a function.
+ Procedure calls are standalone statements,
+ Function calls are made as part of an exoression,
typically on the rigntchand side.
Local and Global Variable
‘Any part of a program can use a global variable - its
scope covers the whole program
+ Alocal variable can only be used by the part of the
program itis declared in its scope Is restricted to that
part ofthe program.
‘Note: Any variables/arrays made in this procedure and
functions will be local and cannot be used out of these.
To be made available all over the program, they must be
declared globally in the following way.
DECLARE [VariableWame] : Datatype AS GLOBAL
6.4, Library Routines
+ Programming language development systems often
provide ibrary routines that can be readily incorporated
into programs.
+ Library routines are pre-tested and ready for use, making.
programming tasks easier.
* Integrated Development Environments (IDES) typically
Include a standard library of funetions and procedures,
+ Standard library routines perform various tasks,
including string hanling,
‘+ MOD - returns the remainder ofa division
+ DIV- returns the quotient (i.e, the whole number part) of
a division
‘+ ROUND - returns a value rounded to a given number of
decimal places
+ RANDOM - returns a random number,
Examples:
WWW.ZNOTES.ORGa a ees
‘+ Valuet <- MOD(10,3) returns the remainder of 10
divided oy 3
+ Value2 <-~ DIV(10,3} returns the quotient of 10 divided
by3
“+ Value3 <-- ROUND(6.97354, 2) returns the value
rounded to 2 decimal places
‘+ Valued <- RANDOM( returns a random number
between 0 and 1 inclusive
65. Creating a Maintainable Program
‘A maintainable program should!
‘+ always use meaningful identifier names for variables,
constants, arrays, procedures and functions
‘+ be dvided into modules for each task using procedures
and functions
+ be fully commented using your programming language's
commenting feature
Commenting in pseudocode:
11 Now the text written 1s coenented and thus ignore
This method can also be used to comment
multiple Lines but the singular Line method
4s none widely accepted and recconended too
6.6. Arrays
‘+ Anarrayis data structure containing several elements
of the same data type; these elements can be accessed
Using the same identifier name,
‘+The position of each element in an array i identified
using the arrays index.
‘+ There are two types of arrays
‘One-Dimensional Array
Explained in the previous chapter in detail
‘Two-Dimensional Array
+ Atwo-dimensional array can be referred to asa table
with rows and columns.
‘+ When a two-dimensional array is declared in
pseudocode, the first and last index values for rows and
the frst and last index values for columns alongside the
data type are included.
Declaring a 20 Array:
DECLARE Name : ARRAY[RowLower:Rowpper, ColumnLower:<
Filling a 2-D array using a loop:
FoR Colunncounter + 1 10 3
FOR RowCounter + 2 10 10
OUTPUT “Enter next value
INPUT ArrayNane [RowCounter, ColunnCounter)
NEXT RowCounter
NEXT coluancounter
6,7. File Handling
+ Computer programs store data that
will be needed again in a file.
+ Data stored in RAM is volatile and will be lost when the
computer is powered off.
+ Data saved toa files stored permanently, allowing itto
be accessed by the same program at a later date or by
other programs.
*+ Stored data ina file can be transferred and used on
other computers.
+The storage of data in files is a commonly used feature in
programming.
WWW.ZNOTES.ORGa a ees
‘Key point: When writing in a file, the program is
‘outputing the data to the file, and when reading a file,
the program In inputing the data from the fle
\n There are 3 ways a file can be opened in a program i.e. to
write, to read and to append
6.8. Writing ina file
OPENFILE "#ilename.txt™ FOR WRITE
/ihinen opening a file to write, all the data already
WRITEFILE “filenane.txt” , Value
11 The next comand of WRITEFTLE would be writen on
CLOSEFILE “Filename. txt’
6.9. Reading a file:
OPENFILE "#ilename.txt™ FOR READ
READFILE “filename.txt” , Variable
// The value in the Line (which is identified by the
CLOSEFILE “filenane. txt
6.10. Reading a file till EOF:
OPENFILE "#Llename.txt” FOR READ
DECLARE OataVariable : STRING
WHILE NOT EOF("Filenane.tet) 00
READFILE “filenane.txt", DataVariable
// here the Line can be outputted or stored in an z
//before the File ends has been read
ENDAHILE
7. Databases
A database is a well-organized compilation of data that
enables individuals to retrieve information according to thelr
specific requirements. The data contained within a database
can encompass various forms such as text, numerical
values, images, or any other type of digital content that can
be stored on a computer system.
7.1. Why do we need a database?
WWW.ZNOTES.ORG
+ To store data about people, things, and events.
‘+ Any mosifications or adsitions need to be made only
once, ensuring data consistency.
+ allusers access and utilize the same set of data,
promoting uniformity.
+ Relational databases store data in a non-repetitive
manner, eliminating duplication,
7.2. What makes a database?
+ Data's stored in tables in databases, Each table consists
of a specific type of data eg. cars, These tables HAVE to
bbe named according to what they contain eg. a table
containing patient information willbe PATIENT
‘+ These tables consist of records (rows). Each record
consists of data about a single entity (a single iter,
person or event) eg. a single car
‘+ These tables also have columns that are knows an fields.
‘These consist of specific information regarding the
‘entities that are writen later in recards e.g car name,
car manufacturer etc
‘Note: In this chapter, skills of dealing with a database
are also required so working with Microsoft Access is
needed to understand this chapter better. You have to be
able to define a single-table database from given data
storage requirements, choose a suitable primary key for
database table and alco be able to read, complete and
understand SQL scripts.
‘Source: Cambridge IGCSE and 0 Level Computer Science by
Hodder Education
7.3. Validation in databasesa a ees
‘+ Database management software automatically provides
some validation checks, while others need to be set up
by the developer during construction,
F example; The software automaticaly validates fields
like “DateOfAdmission” in the PATIENT able to ensure
data input isa valid date. \n
7.4, Basic Data Types
Each field will require a data type to be selected, A data type
classifies how the data s stored, displayed and the
‘operations that can be performed on the stored value
‘The datatypes for database are quite similar to orginal
datatypes, however, there are a few differences
Note: Access datatype refers to the software Microsoft
‘Access which is a DBMS (DataBase Management
System), Here, databases could be worked upon in
practical form
75. Primary Key
‘+ Each record ina table represents a unique item, person,
or event
+ To ensure reliable identification of these ters, afield
called the primary key is necessary.
‘+The primary key is a unique field that distinguishes each
item within che data,
+ Inorder to serve as a primary key, 8 field must have
values that are never repeated within the table.
‘+ An existing field can serve as a primary key iit unique,
such as the ISBN in the book table.
‘+ Incases where all existing fields may contain repeated
data, an additional feld, such as "HospitalNumber," can
bbe added to each record to serve as the primary key.
76. Structured Query Language - SQL
WWW.ZNOTES.ORG
+ Structured Query Language (SQL) is the standara
language for writing scripts to retrieve valuable
information from databases.
+ By sing SQL we can learn how to retrieve and display
specific information needed from a database.
+ For instance, someone visiting a patient may only require
‘the ward number and bed number to locate them in the
hospital, while & consultant may need alist of the names
ofall the patients under their care, This can be done
using SQL
SOL Scripts
+ An SQL scrist sa collection of SQL commands that are
Used to perform a specific task, often stored in a fle for
reusability.
‘+ Toccomprehend SQL and interpret the output of an SQL
script, practical experience in writing SQL scripts is
necessary.
Select Statements:
SELECT (Fieldsnane)
FROM (tablesnane)
WHERE (condition)
(ORDER BY (sortingcondition) 5
Selecting Sum of values in a table:
SELECT SUM ( fieldsrane )
FROM (tablesnane)
WHERE (condition)
(ORDER BY (sortingcondition) 5
Counting the number of records where the field
matches a specified condition
SELECT COUNT ( fielésnane )
FROM (tablesnane)
WHERE (condition)
(ORDER BY (sortingcondition) 5
ORDER BY ASCENDING - sorts in ascending order.
==ORDER BY DESENDING - sorts in descending order.==
Note: ORDER BY...is not necessary fo add. It has to be only
added ifrequirea!a a ees
Condos often nat le am ele hse aes reset by tte i
‘Sim tht wate th te ype or the le
77. Operators
Just tke pseudocode, the operators used there can also be
Used here for conditions, however, a few more are also used
In databases
8, Boolean Logic
8.1. Logic Gates and their functions:
Six types of logic gates
NOT Gate
AND Gate
OR Gate
NAND Gate:
NOR Gate
XOR Gate
NOT gate: an inverter, A
Y
AND gate: A.B
v
ORgate: A+ B
"
NAND gate: A.B
NOR gate: A+B
XOR gate: A@ B
‘schtuetargeata cer oy Pant anstasesl or aea a ees
9. Writing Logic Statements
Logic Statements is a way of showing all the logis that are In
place fora logic circuit.
9.1. Writing from a logic circuit
1. Look at the cult and go around the logic gates used
in the circuit
2. Go from the one output thats being given towards
the input
3. Write the last gate the frst gate you walk through }
in the middle and then, for each ofthe value coming
into the gate, leave space at the side
4, f the value coring nto the gate is coming from
another gate, use a bracket for the gates logic
5. Repeat process 3-4 tllyou are able to reach the input
values fully
9.2, Writing from a truth table
1. Create logic circuit fom the truth table (shown later)
2. Write the logic statement using the cirut
9.3. Writing from a Problem statement
1. See what logics goin place in the statement to take
place
2. Go from the logic of any 2 inputs atthe start, and
then keep on going until you are able to reach the
final gate which gives the output
3. When writing the statement, make sure you show the
logic statement where the output is 1
9.4. Example of a LOGIC STATEMENT
(BAND ©) OR (A NOR (ANAND C)) isthe loge statement for
the following Logic Circuit
10. Creating Truth Tables
10.1. From Logic Circuits
1, Create a truth table with each input possible, creating,
every possible combination of inputs. Tip: For the
first input, write it in the combination of 10,1,0
and so on. For the second, go 1,1,0,0 and so on,
and for the third one, go 1.1.1.1
‘the powers of 2 for each input.
guarantee each possible combination
2, Run through the circut withthe inputs and get the
outpur that will be reached and write it accordingly
For logic statements, and problem statements,
convert them to logic circults first and then do the
rest
10.2. Example
Tiss the example of truth abe ofa ogc eeu
values Valuns a eager
: :
11. Logic Statements from
Truth Tablesa a ees
Input values output
A 8 c x
a 0 ° 1
a o 1 | +
a 1 0 0
0 1 1 1
1 0 0 1
1 a 1 1
1 1 0 1
1 1 1 0
1. Given the truth table above, take the rows where the
‘Output (x) is 1 (ROWS 1, 2, 4,5, 6,7)
2. Create a logic expression fram these rows (example,
row 1 willbe (NOT A AND NOT B AND NOT C) =
3. Create logic expressions forall the rows with output
‘and connect them with OR gate
12. Exam-Style Question
1. The Conditions are given so make logic statements
sing the conditions and the table, (NOT S AND T) OR
(SAND W) OR (NOTTAND W)
2, Make the logic circuit from the given equation
3. Make the truth table
inte 9225 ne dct 8 oun Ags ese. T arent
‘sctunlargeatal seer oy Pant anstasesl or aCAIE IGCSE
Computer Science
Cranes Neo See)
cee ere ener een eee
eee eee een ae eee one metres ee
rhe document contains images and excerpts of text from educational resources avalable on the internet and printed books.
you are the owner of such media, test or visual, utilized in this document and do not accept its usage then we urge you to contact us.
and we would immediately replace sald media. No part of this document may be copied or re-uploaded to another website,
Under no conditions may this document be distributed under the name of false author(s) or sold for financial gain,
"2Notes" and the ZNotes logo are trademarks of ZNotes Education Limited (reg'stration UK00003478331),