0% found this document useful (0 votes)
31 views38 pages

Version To Share - IGCSE Computer Science Notes (Full V)

Uploaded by

Hannah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views38 pages

Version To Share - IGCSE Computer Science Notes (Full V)

Uploaded by

Hannah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

IGCSE Computer Science (0478) Notes

Table of Contents - Syllabus


1 Data representation
1.1 Number systems
Why computers use binary to represent all forms of data
- Any form of data needs to be converted to binary to be processed by a computer
- Bc. data processed by logic gates → which only have two values (0 or 1)
- Denary → base 10 system
- Binary → base 2 (only values 0 and 1)
32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1
- Hexadecimal → base 16 (uses : simplify binary, represent colour + mac address)
0 1 2 3 4 5 6 7 8 9 A B C D E F
Conversion
- Denary → Binary - Hex → Denary
- Eg) 52 → 0011 0000 - Eg) 3B = (3x16 + 11) = 59
- Binary → Denary - Binary → Hex
- Eg) 0101 1101 → 64+16+8+4+1 - Eg) 1110 0101 = E5
→ 93 1110 = 14 = E
- Denary → Hex 0101 = 5 = 5
- Eg) 18/16 = 1 remained 2 → 12 - Hex → Binary
- Eg) 4007 → 250 (15 and 10) and - Eg) 3 = 0011, B = 1011
7 → FA7 3B = 0011 1011

- Why use hex?


- More human friendly than binary
- Because it uses 2 digits when binary uses 8-bits (greater information density)
- Easy to interconvert between hex and binary
- Easier when writing software or diagnosing errors
- Binary addition
- Rules - 11 11
a. 0+0 = 0 1001 1110
b. 0+1 = 1 + 0101 1010
c. 1+0 = 1 __________________
d. 1+1 = 0 carry 1 = 10 1111 1000
e. 1+1+1 = 1 carry 1 = 11
- Eg) 1001 1110 + 0101 1010
- Eg) 1111 0011 + 1010 0101 (example on left)
- 11 111 - Overflow error occurs where an
1111 0011 additional bit is required to store
+ 1010 0101 a result greater than the
__________________ maximum that 8 bits will allow
1 1001 1000 (255)

Binary shift
- Left shift → multiples number by 2
- Right shift → divides number by 2
- Eg) 1101 1001 (217) → right shift → 0110 1100 (108)
- The least significant bit was storing 1. When the right shift occurs this information is lost, resulting in the
number being rounded down & 0.5 is lost
Two’s complement (for negative numbers)
- In 8 bit register, the most significant bit is given the value -128
-128 64 32 16 8 4 2 1
- No difference for positive binary numbers
- Positive → Negative
- Eg) 0010 1011 (43)
- Convert everything (0 → 1, 1 → 0) → 1101 0100
- Add 0000 0001 → 1101 0101 (-43)

1.2 Text, sound and images


ASCII
- ASCII code: a character set for all the characters on a standard keyboard and control codes
- Character set: A list of characters that have been defined by computer hardware & software
- Standard ASCII: 7-bit / Extended ASCII: 8-bit
- ASCII: Uses one byte to represent a character
Unicode
- Unicode: a character set which represents all the languages of the world
- Greater range of characters and symbols than ASCII
- Unicode: support up to four bytes per character (require more bits per character than ASCII)
- ALT + 065 = A (binary = 0100 0001)
Sound → sound wave sampled for sound to be converted to binary + processed by computer
- Sample rate: number of sound samples taken per second
- Sample resolution: number of bits used to represent sound amplitude (bit depth)
- Bit depth: number of bits used to represent smallest unit in a sound file
- Greater resolution + sample rate → greater file size + accuracy of recording
Images → series of pixels converted into binary + processed by computer
- Resolution: # of pixels
- Colour depth: # of bits used to represent colours of a pixel (RGB values between 0-255)
- Greater resolution + colour depth → greater file size + quality of image

1.3 Data storage and compression


- Bit = basic computing element (0 or 1) - 1 MiB = 1024 KiB
- 1 bit = a single 0 or 1 - 1 GiB = 1024 MiB
- 1 byte = 8 bits = 1 character of text - 1 TiB = 1024 GiB
- 1 nibble = 4 bits = half a byte - 1 PiB = 1024 TiB
- 1 KiB = 1024 bytes - 1 EiB = 1024 PiB

- Sound file size (bits) = Sample rate (Hz) x resolution (bits) x duration (s)
- 2 channel = file size x 2
- Image file size = resolution x colour depth
Compression → to reduce size of file
- Necessary to reduce file size because…
- Less bandwidth required, less storage space required, shorter transmission time
- Lossless compression → reduces file size without permanent loss of data (eg. RLE, PNG))
- Run length encoding (RLE)
- Eg) 1 = white, 0 = black
4 ‘1’s and 12 ‘0’s → 4 1 12 0
- First value: number of identical data items / Second value: code of data item
- Effective only when there is long run of repeated units
- Lossy compression → reduces file size by permanently removing data (eg. JPEG, mpeg-3)
- Benefits & drawbacks of increasing sampling rate & resolution
- Benefits
- Larger dynamic range
- Better sound quality
- Less sound distortion
- Drawbacks
- Produce larger files
- Takes longer to transmit / download
- Requires greater processing power
2 Data transmission
2.1 Types and methods of data transmission
- Data broken down into packets to be transmitted
Structure of packet
- Header → destination address + originating address + packet number
- Payload → contents that need to be sent = actual data
- Trailer → data indicating end of packet + checksum
Process of packet switching
- Data broken down into packets
- Each packet could take different route
- Router controls route a packet takes
- Packets may arrive out of order
- Once the last packet has arrived, packets are reordered
Data transmission

Simplex transmission Half duplex transmission Full duplex transmission

- Both directions but not at


- Both directions at the
- One direction only the same time
same time
- Eg) keyboard & computer - Cannot send & receive
- Eg) phone call
- Eg) walkie-talkie

Serial transmission Parallel transmission

- Number of wires used → many bits sent at


- Individual bits sent one bit after another over the same time
a single wire (1 bit at a time) - Eg) CPU & RAM
- Benefits - Data needs to be transferred quickly
- Data can be sent over long distance - Components close to each other →
- Only require one wire = cheaper + skew & crosstalk less of an issue
smaller + allow longer cables - Benefits
without risks of crosstalk and skew - Multiple bits sent at once → fast
- Drawbacks - Drawbacks
- Sending 1 bit at a time → slow - Cable length must be kept short
- Crosstalk + skew

- Crosstalk : signal on one line creates disturbance in another line → cause bits to be reversed
- Skew : signals arrive at slightly diff times because cables have slightly diff properties → receiver needs
to wait until all lines are received

Universal serial bus (USB) → used for transferring data

Benefits Drawbacks

Connected to all devices by simply installing drivers Connections should be 5 m in length before USB hub
is used
Can support different data transmission rates
Data transfer speeds not fast enough to use in internal
No need for external power
devices (CPU, hard drive)
2.2 Methods of error detection
- Transmission errors due to…
- Electrical interference, power surges, synchronisation issues, wear and tear on connector cables
- Errors may cause… data loss, data gain, data change
Error detection
- Parity bit check
- Used to check if there is an error in transmission
- Even parity → total number of 1s must add to an even number
- Odd parity → total number of 1s must add to an odd number
- On every chunk (or byte) sent → parity digit added
- Example in even parity
- If even → parity bit will become 0 to make # of 1s even
- If odd → parity bit will become 1 to make # of 1s even
- If parity bit fails → sender gets notified by receiver + data resent
- Drawback: cannot find exactly which bit is in error
- Parity block check
- Can find which row and column the error is in → can find exact place & correct the bit
- Drawback: cannot detect error if 2 or more number of bits has changed
- Check digits
- Additional digit at the end of set of numbers to check for mistakes in input or transmission
- Receiver notices error → will notify sender
- Eg) ISBN, barcodes
- Check sum
- Created and sent with file
- When received → checksum generated again + compared
- If doesn’t match → file may have been corrupted or altered
- Used for security → downloading softwares + processing credit card
- Echo check
- Data transmitted to receiver
- Same data echoed back to transmitter
- Transmitter compares data with original
- If not the same → data transmitted again
- Drawback: if wrong data received → cannot know if error occurred when sending data at first
or when sending data back to sender for checking
- Automatic Repeat Request (ARQ)
- At transmission, timer starts → sender sends data → receiver sends acknowledgement
- When sender receives acknowledgement → sends next data
- If acknowledgement not received → timeout occurs + data resent
- Positive acknowledgement : when data correctly received → acknowledgement (ACK) sent
- Negative acknowledgement : when receiver detects error in data → negative acknowledgement
(NACK) sent
- Sender doesn’t need to wait in timeout → can immediately resend data
2.3 Encryption
Purpose of encryption when transmitting data
- Encode file or data into something that cannot be read or understood
- Key or password used to decrypt data
- Encrypt → encode into unreadable form
- Decrypt → decode encrypted data back into plaintext
Symmetric encryption
- Key first shared between sender and receiver
- Key encrypts data before transmission → receiver uses key to decrypt data
Asymmetric encryption
- Two keys created by the receiver
- Public key → accessible by anyone and used to encrypt data (shared with sender)
- Private key → kept secret by the receiver and used to decrypt data
- Anyone can encrypt data, but only the receiver can decrypt it
- No need to share a secret key like symmetric encryption
Web asymmetric encryption
- Web pages shared using HTTPS → makes use of encryption
- Browser + server share necessary public keys to encrypt data & use private keys to decrypt data
- If symmetric encryption is used → every website would have to send password privately to you
3 Hardware
3.1 Computer architecture
Central processing unit (CPU) → processes instructions and data that are input so that result can be output
Microprocessor → type of integrated circuit on a single chip
Von Neumann architecture → instructions and data both in same memory (CPU accesses both from same RAM)
RAM → holds all data and programs needed to be accessed by CPU
- CPU takes data and programs held in the backing store and puts them into RAM temporarily (bc.
read/write operations faster in RAM than in backing store)
Components of CPU

Units

Allows required arithmetic (+, -, shifting) & logic operations (AND, OR, NOT) to be
Arithmetic &
carried out
Logic Unit (ALU)
Possible to have more than one ALU to carry out specific functions

Coordinate + control activities in CPU


Decode + execute instruction
Control Unit (CU)
Synchronisation of data flow & instruction (direct timing)
Receives signals from system clock

Registers → fast memory location in CPU itself

Current instruction
Stores current instruction being decoded and executed
register (CIR)

Accumulator
Used when carrying out ALU calculations → stores data temporarily during calculations
(ACC)

Memory address
Stores address of memory location currently being read from or written to
register (MAR)

Memory data Stores data which has just been read from memory or data which is about to be written
register (MDR) to memory

Program counter
Stores address where next instruction to be read can be found
(PC)

Buses → collection of wires through which data or control signals are transmitted

Carries addresses throughout computer system


Address bus Between CPU and memory → unidirectional (prevent address being carried back to CPU)
Wider bus → more memory locations can be directly addressed

Carries data from CPU to memory (+ vice verse) and to & from input/output devices
Data = address, instruction, numerical value
Data bus
Bidirectional (data sent in both directions)
Wider bus → larger word length can be transported → improve performance

Carries signals from control unit to other components → control activities within CPU
Control bus
Unidirectional or bidirectional
Fetch-Decode-Execute cycle
- Fetch → fetch instruction and data involved from main memory
- Decode → instruction decoded so that it can be interpreted
- Execute → CPU passes decoded instruction as control signals
- Steps:
- PC contains address of memory location of next instruction which has to be fetched
- Address copied from PC to MAR by address bus
- Contents/instructions at memory location contained in MAR copied temporarily into MDR
- Contents/instructions of MDR copied into CIR
- Value in PC incremented by 1 → for next instruction to be fetched
- Instruction decoded and executed in ACC by sending out signals by control bus to components
Factors that affect performance of CPU
- Number of cores
- Cores → processing units placed in one CPU (한번에 instruction을 몇개나 처리할 수 있는지)
- One core made up of ALU + control unit + registers
- Using more cores → more need to continually increase clock speeds
- BUT double number of cores doesn’t double performance (케바케)
- Size of cache
- Cache → very fast, expensive memory in CPU (RAM < cache < register)
- Stores frequently used instructions and data → improve CPU performance
- Larger cache memory size → better CPU performance
- Level 1, 2, 3 cache (faster levels tried first)
- Reduces time that CPU has to wait for data from main memory
- Speed of clock
- Clock → cycles per second measured in hertz (Hz)
- Increasing clock speed → increase in processing speed (not necessarily increase in
overall performance)
- Overclocking (clock speed higher than computer designed for)
- Unsynchronised operations (crash + unstable) + overheating
Instruction set → list of all commands that can be processed by CPU
- CPU uses assembly code or machine (binary representation of assembly code) code
- Opcode → informs CPU what operation needs to be done (instructions)
- Eg) STO = store
- Operand → data which needs to be acted on or register in memory (values worked on)
- Eg) 057 = into memory address 057, ACC = contents of accumulator
Embedded system
- Combination of hardware and software designed to carry out specific functions

Benefits Drawbacks

- Small in size → easy to fit into devices - Difficult to upgrade = more thrown
- Relatively low cost to make away than repaired
- Usually dedicated to one task = simple interfaces - Although interface seems more simple,
- Consume very little power actually more confusing
- Very fast reaction to changing input - Can be accessed over internet = open to
- Mass production → reliability hackers / viruses
- Different to general purpose computers that is used to perform many different functions
- PC or laptop NOT embedded system
- Examples
- Cars → GPS system, entertainment systems, airbags, fuel injection system, exhaust emissions,
vehicle security, ABS braking
- Security systems → temperature/pressure/acoustic input, interface remotely
- Lighting systems → Use inputs & data stored considering different factors (eg. time)
- Vending machines → input pad for selection, coin counter, temperature sensors
- Washing machines → keypad or dials for selection

3.2 Input and output devices


Input devices put data → data processed → maybe saved using primary/secondary storage → output devices send
data from computer to user

Input devices → transfer data from source in outside world to computer

- Barcode → series of dark and light parallel lines of varying thickness


- Barcode number looked up in stock database → stock item info sent back + new
value for # of stock written back in record + automatically order stock items
Barcode scanner
- Advantages of barcodes
- To management → allow automatic stock control
- To customers → faster checkout, errors reduced

- Consists of block of small squares (light and dark) = pixels


- Process image taken → convert squares into data + decode any web addresses →
QR code user sent automatically
- Adv than barcodes : hold more info, fewer errors, easier to read (X laser scanners)
- Disadv than barcodes : can transmit malicious codes (to gain access on device)

- Controlled by embedded system


Digital camera
- Uses → photography, security cameras, video conferencing

- Plastic keys + small pieces of rubber under key → make key bounce back up
Keyboard
- Key pressed → make contact with conducting membrane

- Converts sound waves into electric current


Microphone
- Use ADC (analogue to digital convertor)

- Pointing + selecting area of screen


Optical mouse
- Sensor take repeated images of the surface + compare changes

2D scanners - Used to input hard copy (paper) documents → convert into electronic form

- Scan solid objects → produce three-dimensional image (x,y,z coordinates)


3D scanners
- Uses → checking aircraft for damage, create models, medicine, CT scanners

Touch screens → allows to carry out same functions as pointing devices

Capacitive - Composed of layers of glass + electrostatic field change when touched by bare
fingers (bc. human skin is conductor)
- Microcontroller calculate position of change → calculates coordinates

- Array of sensors + infrared transmitters


Infrared - If infrared beams broken (finger touching screen) → infrared radiation reaching
sensors reduced → readings sent to microcontroller → calculates coordinates

- Two layers of electrically resistive material with voltage applied across


- Top layer touched → two layers in contact → circuit complete + electricity flow
Resistive
- Point of contact detected where change in voltage → microcontroller converts
voltage into digital data + sends to microprocessor

Advantages Disadvantages

- Good visibility in strong sunlight - Only work w. bare fingers or special stylus
Capacitive - Durable screen - Sensitive to electromagnetic radiation
- High scratch resistance (magnetic fields or microwaves)

- Multi-touch facility
- Sensitive to water or moisture
- Good durability
Infrared - Accidental activation if beams disturbed
- Operability not affected by
- Sensitive to light interference
scratched or cracked screen

- Low touch sensitivity (press harder)


- Resistant to dust, water - X multi-touch facility
Resistive
- Used with gloves - Poor visibility in strong sunlight
- Vulnerable to scratches (made of polymer)

Output devices

- Used to move mechanisms or systems


Actuator
- Eg. automatic door, central locking on cars, open and close valves

- Produce sound → digital data (binary) changed into analogue data (electric
(Loud) Speaker
current) by DAC + passed through amplifier + loudspeaker converts into sound

Light projectors

Digital light - Mirror for each pixel, rotating wheel RGB (changing colour very quickly)
processing - Adv → high contrast ratio, high longevity, quiet running, small + light
projector (DLP) - Disadv → bad colour saturation, ‘shadows’ when showing moving image

Liquid crystal - 3 LCD screens for RGB, reflected lights (in diff wavelength) all combined by prism
display projector - Adv → sharp image, good colour saturation, efficient energy use, less heat
(LCD) - Disadv → bad contrast ratio, bad longevity (degrade with time)

Screens

Light emitting - Varying electric current sent to each LED → diff brightness → range of colours
diodes (LED) - Uses → large outdoor displays
screen - Adv → brilliance of colours, less power + cost, sharp image, last indefinitely

Liquid crystal - Tiny liquid crystals making up array of pixels affected by changes in electric fields
display (LCD) - Uses → small electronic device + cheap TV (X need good quality display)
screen - Adv → low manufacturing cost

Printer

Thermal bubble technology


- Tiny resistors create heat → ink vaporise → ink form tiny bubble
- Bubble expands → some of ink ejected from print head onto paper
- Bubble collapses → vacuum created → fresh ink drawn into print head
Inkjet printer - Less expensive + BUT only certain ink types used + maintenance cost high
Piezoelectric
- Crystal given electric charge and vibrate → vibration forces ink to be ejected
- More ink drawn in for further printing
- Precise ink size, used for longer periods + BUT more expensive

- Use dry powder ink + use properties of static electricity


Laser printer - Heat make toner stick to page
- Print whole page in one go + use 4 toner cartridges

- Used to produce solid objects in various materials (filaments, resin, ceramic)


3D printer
- Uses → prosthetic limbs, reconstructive surgery, modelling prototypes

Advantages Disadvantages

- Small ink cartridges + paper trays


Inkjet printer
- Inexpensive to buy (frequent changes of ink cartridges)
(few pages of
- Can print on many media types - Expensive ink
good quality)
- Noisy

Laser printer - Large toner cartridges + paper trays - Maintenance costly due to fusers +
(large amount, - Cost per page less (cost effective) large toner cartridges
less quality) - Quiet - Larger in size

Sensor → input devices which read or measure physical properties from surroundings (in analogue form)

Acoustic (sound) Convert detected sound into electric signals/pulses (noise of footsteps in security system)

Accelerometer Measure acceleration and motion of application (measure rapid deceleration for air bags)

Flow (rate) Measure flow rate of moving liquid or gases (respiratory devices in hospitals)

Gas O2 and CO2 sensors + produce output based on gas levels (monitor pollution levels in air)

Humidity Amount of water vapour (monitor humidity levels in air in greenhouse)

Invisible beam of infrared radiation → something breaks beam = diff amount of radiation
Infra-red
reaching detector (security alarm system detecting body heat)
Level Detect changing liquid lvl + measure static conductivity (monitor level in petrol tank in car)

Light Use photoelectric cells that produce output depending on brightness (street lights)

Magnetic field Measure changes in magnetic fields (anti-lock braking systems in cars)

Moisture Measures water levels based on elec. resistance (monitor moisture in soil in greenhouse)

pH Measure acidity through changes in voltages (monitor acidity in soil in greenhouse)

Pressure Generates different electric currents depending on pressure (detect weight of intruder)

Proximity Detect presence of nearby object (mobile phone screen switching off when held to ear)

Temperature Measure temperature of surrounding by sending signals (central heating system)

3.3 Data storage


- Primary storage → directly accessed by CPU
- Contains RAM, ROM, cache memory

Random access memory (RAM) Read only memory (ROM)

Temporary memory device Permanent memory device

Volatile memory (data lost without power) Non-volatile (data not lost even without power)

Can be written to and read from Data stored cannot be altered


Data can be changed by user or computer Can only be read

Used to store data currently in use


Used to store data that computer needs to access
when powering up → BIOS
Can be increased in size to improve speed of computer

- Secondary storage
- Not directly accessed by CPU + necessary for more permanent storage of data
- Non-volatile (data not lost even without power)
- Can be external or internal to computer
- Uses : Hard drive, blu-ray, memory stick, SD card
- Eg) HDD, SSD

Magnetic, optical, solid-state storage


- Magnetic storage : mechanical parts move over disk surface OR drive head read tape
- Platters divided into tracks & sector, mechanical arm
- Data read and written using electromagnets
- Hard disk drives (HDD)
- Process of reading data from hard disk : data written on rotating
platters by RW head + drive spindle rotates + RW head reads data on drive using
electromagnets
- Problem - latency → time for specific block of data on data track to rotate around to
read-write head
- Adv : cheap, large storage, fast speed
- Disadv : many mechanical part, lack durability, X portable
- Solid-state (flash memory)
- Memory chips + non volatile flash + fast R&W
- Uses NAND or NOR technology
- To persistently control flow of electrons (current flowing = 1, no current = 0)
- Benefits over hard disk drives
- More reliable (no moving parts to go wrong)
- Lighter, thin, lower power consumption, cooler than HDDS, faster data access
- Drawback → longevity
- Floating gate and control gate transistors

- Floating gate storing one bit of data


- Floating gate may store or not store electrons
- No electrons present in floating gate → current flow → represent 1
- Electrons stored in floating gate → current doesn’t flow → represent 0
- Optical storage
- Uses lasers to R&W
- CD / DVD disks
- Data stored in pits (튀어나온 부분) and lands (using red laser) → laser burns pits onto
surface of disk
- Optical head moves to point where laser beam contacts disk surface (follows spiral
track from centre to edge)
- DVD → dual layering → increase storage capacity
- Blu-ray discs
- Uses blue laser → smaller wavelength than red = smaller pits → storage capacity↑
- Adv : cheap, portable, little space
- Disadv : ↓ storage capacity, easily damaged, requires CD reader
- Virtual memory

- Part of secondary storage which acts as RAM when RAM is full


- Prevents computer crashing when RAM is full
- Pages of data transferred between RAM and virtual memory when needed (page switching)
- Why it is necessary
- Uses cheap secondary storage on hard drive
- Prevents error messages saying ‘out of memory’ → programs and files will still open
- Cloud storage : allow storage on internet
- Collection of servers that allow data to be accessed remotely
- Available any time, multiple file version, stored in multiple locations
- Controlled by external company (security & privacy)
- Adv : accessed anywhere, stored on multiple servers (reduce risk of data loss), advanced security
features (encryption, multi-factor authentication)
- Disadv : slow or unreliable internet connection → problem with accessing files, storing lot of
data is expensive, data might be intercepted, X have complete control of data

3,4 Network hardware


- Computer needs network interface card (NIC) to access network
- Media Access Control (MAC) address
- NIC given MAC address at point of manufacture
- Usually written in hexadecimal (six groups of hexadecimal digits)
- Manufacturer code + serial code (NN-NN-NN-DD-DD-DD)
- Used to : identify sender + recipient
- 48 bits
- Internet protocol (IP) address
- Global address on internet
- Used to : identify where device is connected
- Static
- ISP (Internet Service Provider) assign permanently to device
- Each device fully traceable
- Upload + download fast
- Dynamic
- ISP assign each time device logs on to internet (using DHCP)
- Greater privacy bc. changes every time
- IPv4 vs IPv6
- IPv4 → based on 32 bits + four groups of eight bits
- Eg. 254.25.28.77
- IPv6 → based on 128 bits + eight groups of hex digits
- Eg. A8FB:7A88:FFF0:0FFF:3D21:2085:66FB:F0FA
- Uses colons
- X risk of IP address collisions
- Built-in authentication checks
- Router
- Sends data to specific destination on network
- Assign IP address
- Connect local network to internet
4 Software
4.1 Types of software and interrupts

Software

System software Application software


(provides services that computer requires) (provides services that user requires)

Operating Device drivers,


Utility software Eg) word processor, spreadsheet, database
system Compilers

Functions of utility software (often just run in the background)

Virus check Constantly check for virus by heuristic checking → quarantine → delete

Files saved to magnetic hard disk (in next available space) → drive head moves more = slow
Disk
Defragmenter puts files into contiguous sectors → reduce head movement = fast access
defragmentation
Not used in SSD because → SSD already quick

Back up Allow schedule for backing files to be made - only if changes were made

Security software Manage access control & user accounts (ID + PW)

Screensavers Supply images on monitor after period of inactivity → automatically logs out (secure)

Communicate with OS & translate into format understood by hardware peripheral device
Device driver
- Descriptors : info about device (vendor ID, product ID, serial number)

Functions of operating system


OS → provides both environment in which applications can run + useable interface btw human and computer

Managing files Copy, save, rename files

Handling interrupts

Providing an interface Allows user to tell computer what to do (GUI, CLI, wimp)

Managing peripherals and drivers Peripheral devices need device drivers (allows OS to access device)

Managing memory Keeps record of where each program & data is stored

OS switch between programs to make use of CPU = as if all are


Managing multitasking
happening at the same time

Providing platform for running applica. When program opened → OS loads program into RAM

Providing system security Users checked by passwords, access restricted, files protected

Managing user accounts Users’ data stored in separate parts of memory


- Hardware, Firmware & the OS
- Applications run on OS → on firmware → on hardware
- Hardware process + send info to OS, directly talks back to AS in continuous loop
- Firmware
- Contains programs stored permanently in hardware → provide low level control
- Bootstrap loader → contains initial boot-up instructions from ROM (when computer
initially first loads up)
- Initial process handled by basic input / output system (BIOS) = firmware
- BIOS → start of motherboard (stored in EEPROM)
- Interrupts
- Signal sent from a device or from software to microprocessor
- Cause microprocessor to temporarily stop what it is doing to service interrupt
- Can be caused by…
- Software interrupts
- Division by zero (priority)
- Data X in RAM, in virtual memory (need to be loaded back to RAM)
- Two processes trying to access same memory location
- Hardware interrupts
- Pressing key on keyboard, moving mouse
- Interrupt service routine (ISR)
- Needs to execute as quickly as possible (방해 CPU)
- Interrupt service routine added to particular area where instructions are sent that will
need to be fetched, decoded, executed to complete commands of interrupt
- What happens as a result of interrupts
- Current registers need to be changed to accommodate interrupt
- Interrupt received → current values that were held in registers copied back to RAM in
an area known as stack
- Values pushed onto stack → added to top of stack frame → save for later retrieval
- Buffer = temporary memory used when downloading movies, etc. (buffering)

HCI (human computer interface)


- Command Line Interface (CLI) → requires user to type in instructions in order to choose options
- Graphical User Interface (GUI) → allows user to interact with a computer using pictures or symbols

Interface Advantages Disadvantages

- Direct communication with computer


- Needs to learn commands to carry
- Not restricted to number of
out basic operation
Command line predetermined options
- All commands need to be typed →
interface (CLI) - Possible to alter computer
takes time + error-prone
configuration settings
- Correct format + spelling
- Uses small amount of memory

- X need to learn commands - Uses up more computer memory


Graphical user - More user-friendly → icons used than CLI
interface (GUI) - Pointing device used to click on icon - Limited to icons provided
to launch application - Needs OS to operate
- Who would use each type of interface
- CLI → programmer, analyst, technician
- Needs direct communication with computer to develop new software
- GUI → end-user who doesn’t have great knowledge of how computer works
- Eg) run software, play games, store photos

4.2 Types of programming language, translators and integrated development environment (IDEs)
- High-level language : independent of computer hardware
- Low-level language : dependent of computer hardware
- Machine code (binary instructions) + assembly language (translated into machine code)

Language Advantages Disadvantages

- Larger programs
- Independent of type of computer being used
- Take longer to execute
High-level - Easier to R, W, U (language closer to English)
- X able to make use of
- Easier + quicker to debug
special hardware

- Can use special hardware


- Takes longer time to W &
- Can include machine-dependent instructions
Low-level debug programs
- Less space in primary memory
- Difficult to understand
- Performs tasks very quickly

Assembly languages
- Form of low-level language that uses mnemonics
- Mnemonics to represent each opcode + denary number or identifier for operand

- Opcode → instruction to be processed


- Operand → value to be operated on / address of value to be operated on
- Register → store values
- Assembler needed to translate an assembly language program into machine code

Translators → converts high level to machine code


- Program translated into binary before used by computer = done by utility program (translator)

Interpreter (developing program) Compiler (translate final program)

- Translates high level language program into - Translates whole code at once before
machine code executing it
- Executes code line-by-line - Produces executable file
- Error detected → displays error message + - Errors detected → error report for whole
stops execution code produced instead of compiled program
- Slower execution (bc. every line translated - Fast execution (bc. whole program ready to
before execution) be executed)
- Cannot run without interpreter - Executed without compiler
- Easy to edit programs + debug and test - Take less space
- Faster when developing program (bc. no - Used when : translating final program
need to compile whole program) - Take time if carried out during development

- Assemblers : translates assembly code into machine code


- Integrated Development Environment (IDE) → programs used to write and test high-level programs
- Code editors → write and edit programming code
- Line numbers → allow programmer to clearly see each line of code
- Syntax highlighting → shows different parts of program by colour of text
- Prettyprint → applies indentation and formatting to code = easier to read
- Auto-completion → gives suggestion for variable names & keywords = improve speed
- Auto-correction → fixes mistakes
- Run-time environment → allows testing program while running + runs program
- Translators → interpreter or compiler (high-level → machine code)
- Error diagnostics → list of errors with line numbers in which they were detected
- Help programmer to find where they have made a mistake

5 The internet and its uses


5.1 The internet and the world wide web
- Internet
- Worldwide collection of interconnected networks and devices
- Infrastructure that allows us to send and receive information
- Makes use of transmission protocols (TCP) and internet protocols (IP)
- World wide web
- Collection of websites and web pages accessed using internet
- Uses internet to access information from web servers
- Http(s) protocols written using hypertext mark-up language (HTML)
- Uniform resource locators (URLs) used to specify location of web pages
- Uniform resource locator (URL)
- Text-based address for a web page
- Protocol → communication protocol used to transfer data between client and server
- Eg. HTTP, HTTPS, FTP
- Domain name → name of server where resource is located
- Web page / file name → location of file or resource on server
- Format → protocol://website address(domain)/path/file name
- Hypertext Transfer Protocol (HTTP)
- Used for transferring data between a client and server in internet
- Doesn’t store any information about previous requests or responses
- Hypertext Transfer Protocol Secure (HTTPS)
- Secure version of HTTP, uses encryption to protect data transferred between client and server
- Harder for unauthorised users to intercept or manipulate data
- Purpose of web browser → render hypertext markup language (HTML) + display web pages
- Functions
- Storing bookmarks and favourites - Storing cookies
- Recording user history - Providing navigation tools
- Allowing use of multiple tabs - Providing an address bar
- How web pages are located, retrieved, and displayed on device when user enters a URL
- Role of Domain name server (DNS) → finds matching IP addresses for URL + sends IP address
to web browser
- Steps:
- User opens web browser + types in URL → browser asks DNS server 1 for IP address
- DNS server 1 cannot find required website → sends out request to DNS server 2
- DNS server 2 finds URL → sends IP address back to DNS server 1 → DNS server 1
puts IP address and URL to its database & cache
- IP address sent to computer + computer sets communication with website server +
required pages are downloaded
- User’s browser interprets HTML + displays web pages on computer
- Cookies
- Small files that are stored on user’s device by a website
- Functions → saving personal details, tracking user preferences, holding items in an online
shopping cart, storing login details
- Session cookies
- Temporary + stored only during user’s browning session
- Used to maintain user’s state or activity during single session
- Persistent cookies
- Stored on user’s device for longer period
- Used to remember user preferences and settings
- Enhance user experience + more convenient for users to interact with websites
- But also raise privacy concerns + should be used responsibly by website owners

5.2 Digital currency


- Digital currency → only exists electronically
- Decentralised, used for transactions, volatile
- Blockchain → digital ledger, records every transaction made with a particular digital currency
- First block = genesis block
- Blocks policed by network users called ‘miners’
- Values created for new block → data, hash value, previous hash value
- Not controlled by single entity or authority
- Every participant in the network has copy of ledger + can verify transactions independently
- Each transaction must be verified by multiple participants in network
- Verification process ensures that transaction is legitimate + prevents any fraudulent activity
- Digital currency vs cryptocurrency
- Crypto → use cryptography to track transactions, decentralised, block chaining, publicly
available
- Digital → central banking system
5.3 Cyber security

Threats

Brute-force attack Data interception

- Eavesdropping to intercept + steal sensitive


- Trial-and-error method → try every possible
information
combination until correct one is found
- Aim → steal sensitive information for
- Aim → gain unauthorised access
personal gain + for further cyber attacks

Distributed denial of service (DDoS) attack Hacking

- Multiple computers used as bots - Gaining unauthorised access to steal or


- Flood server with lots of requests at the same manipulate data, disrupt services, or cause
time → cause crash damage
- Aim → disrupt normal functioning of system - Aim → vary from personal gain to activism
or network by denying users access or cyber espionage

Malware → designed to harm or gain unauthorised access

Virus Worm

- Code that attaches to legitimate program


- Similar to virus but it self replicates + doesn't
- Replicates with intention of deleting or
need active host
corrupting files + need active host

Trojan horse Spyware & Adware

- Spyware → records key presses + transmits


- Program that disguises as legitimate program
to third party
- Can delete data or damage hardware when
- Adware → displays unwanted advertisements
installed
on computer without user’s consent

Ransomware Social engineering

- Involves manipulating individuals to gain


- Encrypts user’s files and demands ransom
access to confidential information or to
payment to decrypt them
perform an action that benefits the attacker
- Can cause data loss, financial damage,
- Aim → exploit human behaviour and
disrupt business operations
vulnerabilities to gain unauthorised access

Pharming Phishing

- User sent an email which looks legitimate


- Malware being downloaded without user’s - Contains link to fake website where user is
knowledge encouraged to enter their details
- Redirects user to fake website - Aim → steal sensitive information for
personal gain + for further cyber attacks
Solutions

Access levels Anti-malware (anti-virus + anti-spyware)

- Prevent and remove malware


- Used to restrict access to sensitive - Anti-spyware → detects + removes spyware
information to only authorised personnel programs installed illegally
- Prevents unauthorised access - Scan files → compare files to list of known
- Full access, read-only access, no access malware → if malware found, quarantine →
deleted

Authentication (username, password, biometrics,


Firewalls
two-step verification)

- Ensure that only authorised users access data


- Monitors incoming and outgoing traffic
- Biometrics → uses biological data by unique
between computer and network
physical characteristics (eg. fingerprints,
- User sets criteria for traffic → traffic
facial recognition, iris scans)
compared → accept or reject traffic based on
- Two-step verification → requires 2 forms of
this → alert sent to user = prevent hacking
authentication (eg. pw + verification code) +
- Warn if something is trying to excess
extra layer of security reducing risk of
- Only allow trusted IP
unauthorised access

Privacy settings Automating software updates

- Control amount of personal info shared - Ensures that software systems are uptodate

Checking spelling and tone of communications Checking URL attached to link

- To prevent phishing attacks - To prevent phishing attacks

Proxy-servers Secure socket layer (SSL) security protocol

- Hide user’s IP address and location →


- Security protocol
difficult for hackers to track them
- Encrypt data transmitted
- Act as firewall + used to filter web traffic by
- Prevent data interception
setting criteria for traffic
- Used in online transactions
- Malicious content blocked + warning
- Sends digital certificate to browser (contains
message sent to user
public key for authentication)
- Protect against external security threats +
- Authentication → transaction will begin
direct traffic away from server

VPN Proxy-server

- User → ISP (eg. SKT, KT) → Website


- Hide user’s IP address
- ISP knows what website you visited (ISP를
- Difficult for hacker to track
통해서 website access ← X)
- Act as firewall and filter web traffic
- If VPN used : User → ISP → VPN → Website
- Malicious content blocked
- VPN calls website → ISP X know website
6 Automated and emerging technologies
6.1 Automated systems
Automated systems
- Combination of software and hardware that is designed and programmed to work automatically without
need of any human intervention
- Sensors → detect changes in env. + convert them into electrical signals to be processed by microprocessor
- Microprocessors → analyse signals from sensors + make decisions based on pre-programmed logic
- Actuators → receive signals from the microprocessor + perform actions
- Eg) opening a valve or turning on a motor

Scenario Advantages Disadvantages

- High initial investment


Industry - Reduced labour costs
- Limited flexibility to changes in
(nuclear power - Improved efficiency + accuracy
production processes
station) - Increased production rate
- Maintenance costs can be high

Transport - High initial investment


- Reduced labour costs
(self-parking - May not be suitable for all types of
- Improved safety and reliability
cars, adaptive transportation
- Improved fuel efficiency
cruise control) - Maintenance costs can be high

- Reduced labour costs - High initial investment


Agriculture
- Increased efficiency in planting - May not be suitable for all types of
(irrigation
and harvesting crops crops
system)
- Improved crop yield and quality - Maintenance costs can be high

- Improved accuracy in prediction - May be affected by external factors


- Ability to issue warnings in a like interference or equipment failure
Weather timely manner - May not be 100% accurate
- Ability to collect large amounts - May require continuous monitoring
of data quickly and calibration

- Reduced labour costs - May not be suitable for all types


- Improved speed and efficiency in - May require significant programming
Gaming game development expertise
- Ability to create complex and - May be affected by technical glitches
interactive games or bugs

- Reduced labour costs - High initial investment


Lighting
- Improved energy efficiency - May not be suitable for all types of
(house lighting
- Ability to program lighting to lighting needs
system)
suit different needs - Maintenance costs can be high

- Reduced labour costs - High initial investment


Science - Improved speed and accuracy in - May not be suitable for all types of
(chemical data collection and analysis experiments
process in lab) - Ability to carry out complex - May require significant technical
experiments expertise
6.2 Robotics
- Def → branch of computer science that incorporates the design, construction and operation of robots
- Design and construction :
- Designed using combination for mechanical, electrical, computer engineering
- Robotic design customised to meet specific needs
- Operation :
- Needs to be programmed to carry out specific tasks
- Involves creating set of instructions that tell robot what actions to perform
- Robot’s sensors used to detect and respond to changes
- Operated remotely using controller
- Example :
- Factory equipment (welding, painting, assembling products)
- Domestic robots (designed to perform household chores)
- Drones (unmanned aerial vehicles used for tasks like aerial photography, delivery,
surveillance)
- Characteristics
- Robot → machine that can be programmed to carry out a range of tasks autonomously or
semi-autonomously
- Have a mechanical structure or framework → physical body to move and interact
- Electrical components (such as sensors, microprocessors, actuators) → allow robots to receive
information and respond
- Programmable → designed to follow set of instructions or algorithms (allow them to complete a
variety of tasks + respond to changing situations)
- Roles
- Industry → manufacturing and assembly lines to increase productivity + accuracy
- Adv : capable of working in hazardous conditions, no need to stop, less expensive in
long run, more productive, consistent
- Disadv : lead to unemployment, expensive to set up in the first place, difficult to do
‘non-standard’ tasks
- Transport → warehouses and logistics to move and transport goods (eg. autonomous vehicles)
- Adv : safer since fewer accidents, better for environment, reduced traffic congestion,
reduced travel time
- Disadv : expensive to set up, ever-present fear of hacking, safety issues, reluctance to
use new technology
- Agriculture → tasks such as planting, harvesting, spraying crops
- Medicine → surgical procedures to increase precision and reduce risk of errors
- Domestic → tasks such as vacuuming, lawn mowing, cleaning
- Entertainment → toys or in amusement parks to provide entertainment

Advantages Disadvantages

- Increased productivity → work continuously - High initial investment → purchasing and


without breaks or fatigue setting up robots can be expensive

- Consistency and accuracy → perform tasks - Maintenance costs → require regular


with a high level of precision and accuracy maintenance and repairs (add to overall cost)

- Lack of flexibility → programmed for


- Safety → perform tasks that are dangerous or
specific tasks and cannot adapt easily to new
hazardous for humans
situations or tasks

- Cost-effective → help reduce labour costs in - Unemployment → lead to job loss in certain
long run industries

6.3 Artificial intelligence


Artificial intelligence
- Def → branch of computer science dealing with the simulation of intelligent behaviours by computers
- Goal of AI → simulate intelligent behaviour in machines including :
- Problem-solving, decision-making, natural language processing
- Used in areas such as : robotics, natural language processing, expert systems, machine learning
Characteristics of AI
- Collection of data and rules
- AI system require large amount of data to perform tasks
- Data processed using rules or algorithms that enable system to make decisions and predictions
- Ability to reason
- Use logical reasoning to evaluate information + make decisions based on that information
- Ability to learn and adapt
- Can change its own rules and data
- Can be designed to learn from past experiences and adjust their behaviour accordingly
Types of AI systems
- Expert systems
- Have a knowledge base
- Database of facts to generate rules that are used to solve problems + make decisions
- Have a rule base
- Set of rules or logic used to apply knowledge in the knowledge base to specific
problems
- Have an inference engine
- Program that applies the rules in rule base to facts in knowledge base to solve problems
- Forward chaining : give number of facts to the system → inference engine uses to reach
new facts
- Backward chaining : give goal → determine facts needed to reach that goal
- Have an interface
- Way for users to interact with system and provide input
- Eg) web pages, chat bots, telephone systems
- Adv : high accuracy, consistent result, able to store vast amounts of facts, traceable logical
solutions, very fast response times
- Disadv : need considerable training, set up expensive
- Machine learning
- When program has the ability to automatically adapt its own processes and/or data
- Uses algorithms to analyse data and identify patterns and relationships
- System can learn from data and improve its performance over time
- AI vs Machine learning
- AI → represents simulated intelligence in machines
- Aim : build machines that are capable of thinking like humans
- Machine learning → practice of getting machines to make decisions without being
programmed to do so
- Aim : make machines that learn through data acquisition, so that they can
solve new problems
7 Algorithm design and problem-solving
Development Life Cycle

Stages of program development life cycle

- Specification of what a program is required to do


Analysis - Abstraction (unnecessary details discarded), decomposition of the problem (breaking down
problem into smaller parts), identification of the problem and requirements

- Uses program specification from analysis stage to show how program should be developed
Design
- Decomposition, structure diagrams, flowcharts, pseudocode

- Writing program code + iterative testing


Coding - Iterative testing → modular tests conducted, code amended, tests repeated until
module performs are required

- Testing program code with use of test data → to make sure that it works under all
Testing
conditions

Computer systems, sub-systems and decomposition


- Every computer system made up of sub-systems which are made up of further sub-systems
- Made up of software, data, hardware, communications, people
- Component parts of computer system:
- Inputs → data used by system that needs to be entered while system is active
- Outputs → information that needs to be displayed or printed for users of system
- Processes → tasks that need to be performed using input data and other previously stored data
- Storage → data that needs to be stored in files on appropriate medium for use in future

Methods used to design and construct a solution to a problem

- Used to show top-down design in a diagrammatic form


Structure diagrams - Top-down → breaking down of computer system into set of subsystems until
each performs a single action

- Steps required for a certain task written in a diagrammatic form

Begin / End
Process Input / Output Decision Flowline
(Terminator)
Flowcharts

- Simple instructions that use English-like words and mathematical operators to


write up a program
Pseudocode
- Advantage → allows to focus on logic of algorithm without being distracted by
exact syntax of programming language
Algorithm
- Purpose of algorithm
- Set of steps to complete a certain task
- Usually shown as a flowchart or pseudocode

Standard methods of solution

Totalling Counting

Keeping a total that values are added to Keeping number of times of an action is performed

PassCount ← 0
FOR Counter ← 1 TO ClassSize
INPUT StudentMark
IF StudentMark > 50
THEN
PassCount ← PassCount + 1
Total ← 0 ENDIF
FOR Counter ← 1 TO ClassSize NEXT Counter
Total ← Total + StudentMark[Counter] Count ← Count + 1

NEXT Counter
Counting until a certain value:
NumberInStock ← NumberInStock - 1
IF NumberInStock < 20
THEN
CALL Reorder()

Finding maximum & minimum Finding average (mean)

Max ← StudentMark[1] // set min and max as first item in the list
Min ← StudentMark[1]
FOR Counter ← 2 TO ClassSize
IF StudentMark[Counter] > Max
THEN
Max ← StudentMark[Counter] Total ← 0
ENDIF
Count ← 0
IF StudentMark[Counter] < Min
THEN Average ← 0
Min ← StudentMark[Counter] WHILE SushiDetected
ENDIF
Total ← Total + Price
NEXT Counter
Count ← Count + 1
Example - Only finding min or max: ENDWHILE
Min ← 0 Average ← Total / Count
First ← TRUE
OUTPUT Average
WHILE SushiDetected
IF First THEN
Min ← Price
ELSE
First ← FALSE
IF Price < Min THEN
Min ← Price

Linear search Bubble sort

Each element compared with next element


Inspects each item in a list in turn to see if the item Swapped if elements are in wrong order (from first element
matches the value searched for and finishing with next-to last element)
Reaches end of list → sure that this last element is in correct
place
Each element in list compared again apart from last one →
continues to repeat until…
- Only one element left to check
- No swaps are made

DECLARE StudentName[1:3] AS STRING


StudentName = [“djfkdj”, “djfkdjfkd”, “djfkdjkfd”]
OUTPUT “Please enter name to find” First ← 1
INPUT Name Last ← 10
Found ← FALSE REPEAT
Counter ← 1 Swap ← FALSE
REPEAT
FOR Index ← First TO Last - 1
IF Name = StudentName[Counter] THEN
IF Temperature[Index] > Temperature[Index + 1]
Found ← TRUE
ELSE THEN
Counter ← Counter + 1 Temp ← Temperature[Index]
ENDIF Temperature[Index] ← Temperature[Index + 1]
UNTIL Found OR Counter > ClassSize Temperature[Index + 1] ← Temp // Temp
IF Found variable is temporary
#output
Swap ← TRUE
ENDIF
Example - How many has that option
ChoiceCount ← 0 NEXT Index
FOR Counter ← 1 TO Length Last ← Last - 1
IF “ice cream” = Dessert[Counter] THEN UNTIL (NOT Swap) OR Last = 1
ChoiceCount ← ChoiceCount + 1
NEXT Counter
OUTPUT ChoiceCount, “ chose ice cream as their favourite dessert.”

Validation and verification


- Validation → ensures that only reasonable data is accepted

Range check Length check

Value between upper value & lower value Contains exact number of characters (eg. 8 char)
- Eg) % marks between 0 and 100 inclusive OR is a reasonable number of characters (2~30 char)

ValidNameLength ← FALSE
ValidAge ← FALSE
Name ← ""
Age ← 0
WHILE NOT ValidNameLength DO
WHILE NOT ValidAge DO
INPUT Name
INPUT Age
IF LENGTH(Name) >= 8
IF Age >= 0 AND Age <= 120 THEN
THEN
ValidAge ← TRUE
ValidNameLength ← TRUE
ENDIF
ENDIF
ENDWHILE
ENDWHILE

Type check Presence check

Data entered is a given data type Some data has been entered & not been left blank
- Eg. Number of siblings = integer - Eg. Email address must be completed

INPUT Length UsernameEntered ← FALSE


IF Type(Length, Integer) Username ← ""
THEN WHILE NOT UsernameEntered DO
OUTPUT "Valid number" INPUT Username
ELSE IF Username <> ""
OUTPUT "Invalid – not an integer" THEN
ENDIF UsernameEntered ← TRUE

Format check Check digits

Characters entered conform to predefined pattern


- Eg. Rooms include number and letter

Data entry check, not data transmission check


INPUT Username
Final digit included in code, calculated from all the
IF Username.isalpha():
other digits
OUTPUT "Valid - all letters"
Used to identify errors in data entry caused by
mis-typing or mis-scanning a barcode
Incorrect digit, Transposition errors, omitted or extra
digits, phonetic errors

- Verification → used to check that data does not change as it is being entered

Double entry check Visual check

- Manual check completed by user entering


- Data entered twice, sometimes by different
the data
operators
- Data displayed and user asked to confirm
- Compare both entries
that it is correct

Test data

Normal data Test data used that program would normally be expected to work with

Test data chosen to be rejected by solutions as not suitable (if program is working
Abnormal data
properly)

Extreme data Largest and smallest values that normal data can take

Two values required: one accepted, other rejected


Boundary data Largest and smallest acceptable value + smallest and largest rejected value
Eg) Boundary for 0 is: -1, 0 (-1 rejected, 0 accepted)

Trace tables to document dry runs of algorithms


- Used to record value of an item/variable each time that it changes
- Dry run → Manual exercise of working through an algorithm step by step
- Row → each iteration of algorithm, Column → each variable + one for output
- Test data used to dry run the flowchart → record results on trace table

Identifying errors in algorithms

Syntax error Code written doesn’t follow the rules of language


Logical error Program runs, but doesn’t work as the programmer intended

Nothing wrong with syntax or logic


Runtime error Only happens when program is running
Eg) Zero division error → division by zero (cannot be done)

8 Programming
8.1 Programming concepts
Assignment statement
- Value assigned to an item/variable using “←” operator
Basic data types
- Integer → whole number (Eg. 5, -3)
- Real → number capable of containing a fractional part like float (Eg. 4.7, -4.0, 0.3)
- Char → single character (Eg. ‘x’, ‘@’)
- String → sequence of zero or more characters (Eg. “This is a string”, “”)
- Boolean → logical values true and false (TRUE, FALSE)
Input and output statements:
- Input → Eg) INPUT Name
- Output → Eg) OUTPUT “Your name is ”, Name
Sequence
- Statements executed one by one in order they are written

Selection

IF … THEN … ELSE … ENDIF CASE OF … OTHERWISE … ENDCASE

Boolean example:
IF Found
THEN
OUTPUT “Your search was successful”
ELSE CASE OF Grade
OUTPUT “Your search was unsuccessful” “A” : OUTPUT “Excellent”
ENDIF
“B” : OUTPUT “Good”
“C” : OUTPUT “Average”
Comparison example:
IF Age < 18 OTHERWISE OUTPUT “Improvement is needed”
THEN ENDCASE
OUTPUT “Child”
ELSE
OUTPUT “Adult”
ENDIF

Iteration

FOR … TO … NEXT REPEAT … UNTIL WHILE … DO … ENDWHILE


(count-controlled loop) (post-condition loops) (pre-condition loops)

Number of repeats not known Number of repeats not known


A set number of repetitions
Completed at least once May never be completed
FOR Counter ← 1 TO 10
Total ← 0 Total ← 0
OUTPUT “*”
Mark ← 0 INPUT Mark
NEXT Counter
REPEAT WHILE Mark <> -1 DO
Total ← Total + Mark Total ← Total + Mark
Step example:
OUTPUT “Enter value for mark, -1 OUTPUT “Enter value for mark, -1
FOR i ← 0 TO 6 STEP 2
to finish” to finish”
OUTPUT i
INPUT Mark INPUT Mark
NEXT i
UNTIL Mark = -1 ENDWHILE
Output: 0, 2, 4, 6

String handling / String operations

Returns integer value of length of string


LENGTH(<identifier>)
Identifier must be a string

Returns string/character with all lower case


LCASE(<identifier>)
Identifier must be string or char

Returns string/character with all upper case


UCASE(<identifier>)
Identifier must be string or char

Returns string of length <length> starting at position <start>


SUBSTRING(<identifier>, Identifier must be a string
<start>, <length>) Length and start must be positive + integer
Eg) SUBSTRING(“Happy Days”, 1, 5) will return “Happy”

The first character of the string can be position zero or one

Arithmetic, logical, boolean operators


- Arithmetic → +, -, /, *, ^, MOD, DIV
- Logical → =, <, <=, >, >=, <>
- Boolean → AND, OR, NOT
Nested statements
- Statement inside/part of another statement
- Nested selection + nested iteration
Procedures, function, parameters
- Procedure → set of programming statements grouped together to perform a task (may not return value)
- Function → sequence of program instructions that performs a specific task, packaged as a unit (can be
used multiple times) + return value after processing (procedure doesn’t)
- Parameter = variable that store values of arguments passed to a procedure or function
- Used as variable in function
- Subroutines → allow code to be used a number of times by grouping together under one name
- Advantages → can reuse code = more maintainable code
- Both functions & procedures are subroutines
- Without parameters:
PROCEDURE <identifier>
<statements>
ENDPROCEDURE
- With parameters:
PROCEDURE <identifier>(<param1>:<datatype>, <param2>:<datatype>...)
<statements>
ENDPROCEDURE
- param1, param2 → identifiers for parameters of procedure
- Will be used as variables in statements of procedure

Local & global variables


- Local variables
- Exist while function or procedure is executing
- Only accessible within particular function or procedure
- Global variables
- Accessible anywhere in program
- Advantages of using local variables
- Keep a subroutine self-contained
- Used in any program without variable names conflicting with those used in calling program
Library routines
- MOD → remainder when dividing → Eg) 5 MOD 3 = 2
- DIV → integer division → Eg) 100 DIV 3 = 33
- ROUND → return nearest integer of given number → Format → ROUND(<identifier>, <places>)
- RANDOM → returns random number between 0 and 1 inclusive
How to create a maintainable program
- Appropriate use of → meaningful identifiers, comments, procedures and functions
- Use meaningful identifiers (meaningful names) → variables, constants, arrays, procedures and functions

8.2 Arrays
- Fixed-length structures of elements of identical data type (first index can be zero or one)
- Declare one-dimensional array
- DECLARE <identifier> : ARRAY[<l>:<u>] OF <data type>
- Eg) DECLARE StudentNames : ARRAY[1:30] OF STRING
- Declare two-dimensional array
- DECLARE <identifier> : ARRAY[<l1>:<u1>, <l2>:<u2>] OF <data type>
- DECLARE NoughtsAndCrosses : ARRAY[1:3, 1:3] OF CHAR
- Examples of using one-dimensional array
- StudentNames[1] ← "Ali"
- NoughtsAndCrosses[2,3] ← ꞌXꞌ
- StudentNames[n+1] ← StudentNames[n]
- Example of assigning group of array elements
- FOR Index ← 1 TO 30
StudentNames[Index] ← ""
NEXT Index

8.3 File handling


Purpose of storing data in files
- RAM → primary storage + volatile (temporary)
- Files stored in secondary storage → non-volatile (permanent)
- Files may be shared with other users or computers (can be accessed by multiple users)
Creating a file
- OPENFILE FileA.txt FOR WRITE
- File needs to be opened before it can be written to
- Opening file in WRITE mode → create a new file → lose original data if file already existed
Reading from a text file
- Opening the file + processing each line + closing file
- OPEN marks.txt FOR READ // Open file
WHILE NOT EndOfFile DO // Loop through each line in file
READFILE marks.txt, line // Read next line
OUTPUT line // Output line
ENDWHILE
CLOSEFILE marks.txt // Close file
Writing data to a text file
- OPENFILE marks.txt FOR WRITE
INPUT name
INPUT mark
record ← name + “,” + mark + “(backslash)n”
WRITEFILE marks.txt, record
CLOSEFILE marks.txt
- Eg) name = Sandra, mark = 85
Sandra, 85 ← will be added to file
Closing a file
- Once finished reading or writing to a file → need to close it
- CLOSEFILE filename

9 Databases
- Database → structured collection of data that allows people to extract information in a way that meets
their needs
- Useful because : changes need to be made only once, same data used by everyone, no data duplication
- Uses : patients in hospital, books in library, hotel bookings

- Table → contains data


- Record (row) → contains data about single item, every record contains same number of fields
- Field (column) → each field in record contains specific piece of information about single item
- Validation → ensures that only reasonable data is accepted
- Range, length, type, presence, format check
- Verification → checks that the data does not change as it is being entered
- Double entry, screen check
Basic data types
- Data type selected for each field

Data type Description Access data type

Text/alphanumeric Number of characters Short text/long text

Character Single character Short text with field size of one

Boolean True or False (1 or 0, Yes or No) Yes/No

Integer Whole number Number formatted as fixed with zero


decimal places

Real Decimal number Number formatted as decimal

Date/time Date and/or time Date/time

Primary keys
- Primary key → field that uniquely identifies the item
- Purpose → to reliably identify an item from the data stored
- Why existing fields cannot be used as primary key → could contain repeated data
Structured Query Language (SQL)
- SQL → writing scripts to obtain useful information from a database
- SQL script → list of SQL commands that perform a given task
- SQL command
- Starts with…
SELECT __(field name)__
FROM __(table name)__
(Other commands optional)
Ends with ; to show end of command
- SELECT → fetches specified fields from a table
- SELECT Field1, Field2, Field3 → specifies fields to be shown
- SELECT * → specifies that all fields are to be shown
- FROM → identifies table to use
- WHERE → includes only records that matches given condition
- WHERE Condition → specifies condition to apply
- Conditions include…
- Values from fields (matches with data type of field)
- Operators (=, >, >=,< >, BETWEEN, LIKE, IN, AND, OR, NOT)
- ORDER BY → sorts results either alphabetically or numerically
- ORDER BY Field1, Field2 → sort in ascending / alphabetical order from first field
- ORDER by Field1, Field2 DESC → sort in descending / reverse alphabetical order
- SUM
- SELECT SUM (Field) → sum of all values in a field (field should be integer or real)
- COUNT
- SELECT COUNT (Field) → Counts number of records in a field
10 Boolean logic
- Building block of digital circuit
- Perform logical operation on one or more binary inputs to produce binary output
- Electrical signal entering logic gate → 1 / No electrical signal → 0
- NOT = single input gate / All other gates = limited to two inputs

Gate Symbol Function

Takes one binary input → outputs


Input Output
opposite of input
X = NOT A
A X
NOT
0 1

1 0

Input Output

Takes two inputs → produces one


A B X
output
X = A AND B 0 0 0
AND
0 1 0

1 0 0

1 1 1

Input Output

Takes two inputs → produces one


A B X
output
X = A OR B 0 0 0
OR
0 1 1

1 0 1

1 1 1

AND gate + NOT gate


NAND
X = A NAND B Input Output
A B X

0 0 1

0 1 1

1 0 1

1 1 0

Input Output

OR gate + NOT gate A B X


X = A NOR B
0 0 1
NOR
0 1 0

1 0 0

1 1 0

Input Output

Exclusive OR A B X
X = A XOR B
0 0 0
XOR
0 1 1

1 0 1

1 1 0

Gate What it means Gate What it means

NOT Input의 반대 NAND 둘다 1일때만 0


나머지는 1

AND 둘다 1일때만 1 NOR 둘중에 하나가 1이면 0


나머지는 0 0 0 일때만 1

OR 둘중에 하나가 1이면 1 XOR 같으면 0


0 0 일때만 0 다르면 1
From truth table to logic expression → Output에 1이 나오는 애들을 나타냄

A B C X

0 0 0 1

0 0 1 0

0 1 0 0

0 1 1 0

1 0 0 1

1 0 1 0

1 1 0 1

1 1 1 0

= (NOT A AND NOT B AND NOT C) OR (A AND NOT B AND NOT C) OR (A AND B AND NOT C)

You might also like