Computer Science Unit 7
Computer Science Unit 7
Computer Science Unit 7
7.2
What’s an algorithm?
- Create
- Interpret
- Correct
- Refine
Flowcharts: A flowchart is a method of representing the sequences of steps in an algorithm in the form
of a diagram
Writing pseudocode allows us to lay down the logic of a problem in a “almost like a real code” way
without having to worry about the actual strict rule.
Programming
1.Programming concepts
2. Data types
3. Variable constant
1. Programming concepts
- operator use – arithmetic for calculations, logical and Boolean for decisions
2. Data types
Date – A date consisting of day, month and year, sometimes including a time in hours, minutes and
seconds.
CONSTANT PI = 3.142
Python
Print(“Wonderful achievement!”)
Else:
- Data structures are the way we are able to store and retrieve data
List/Array
- An array is a data structure that stores a list of values of the same data type
- An array is a data structure with a fixed size for storing multiple values for the same data type
FOR I 1 to 300
Next I
FOR I 1 – 20
Next I
INPUT Score[Count]
Count 1
INPUT Score[Score]
Count Count + 1
ENDWHILE
Count 1
REPEAT
INPUT Score[Count]
Count Count + 1
NEXT
NEXT
MyList=[]
Print(MyList)
MyTable=[]
Column=[]
MyTable.append(Column)
Print(MyTable)
Numbers = [2, 5, 3, 6, 2, 3, 6, 4]
total 0
LengthofArray = len(8)
NEXT
Numbers = [2, 5, 3, 6, 2, 3, 6, 4]
Total = 0
Total=total + number(i)
Print (total)
Total = 0
Total=total + number(i)
Print (total)
INPUT Distance
INPUT Passengers
Extra = Distance – 1
CostofExtra = Extra * 2
Cost = 3 + CostofExtra
Surcharge = Cost/2
END IF
OUTPUT Cost
Success = False
Try: int(Teddy_bears)
Success = False
Try:
Hourse = int(hours)
Success = True
PerTeddy = 2*TeddyBears
PerHour = 5*Hours
Choice = 0
Abnormal inputs: Data should be rejected by the program – includes no input when one is expected
Boundary inputs: Data is the largest/smallest acceptable value as well as the corresponding
smallest/largest rejected value
VALIDATION
Input validation: means checking that data input by the user meets specific criteria/rules before
processing
Type check: The input is of the correct data type – e.g., int, real, str.
Range check: The input is within a predetermined range – e.g., between 1 and 2
Presence check: All required data has been entered – e.g., reject blank inputs
Length check: The input includes the correct/minimum/maximum numbers of characters – e.g.,
password
UNIT 1, 7, 8
Sample resolution
Image representation
Image resolution
Kilo 1000
Mega 1,000,000
Giga 1,000,000,000
File compression
Two complement
Negative representation
Data skewing
Data packet
Parity bit
Pseudocode
Verification check
ELSE
ELSE
END IF
END IF
REPEAT
INPUT password
IF LENGTH(password) > 12
THEN
ELSE
END IF
END IF
VERIFICATION
Verification: ensures that data is not changed, either accidentally or purpose, as it is entered
Double entry verification is a process whereby important data has been entered twice, sometimes by
different people. The system compares both entries to check they are the same before accepting the
data
A screen check or visual check is a manual check performed by the user who is entering the data
Entering a telephone number: the number needs to be the one that is required as well as having the
necessary characteristics. DOUBLE ENTRY + SMS
Entering a pupil’s name: the name needs to be the one that is associated with the pupil
Entering a part number in the for XXX999, when X must be a letter and 9 must be a digit: a part number
could have the required format but not be for the part intended
Syntax errors: are errors that break the grammatical rules of the programming language and prevent it
from being run or translated
Logic errors: are errors that produce unexpected output but won’t stop the program running
- Easier to manufacture
Compression reduces the size of a file so it takes up less space, helping to maximize the amount of data
we can store in our storage
Homework:
def km2miles(num):
try: option = int(input("""Choose an option to convert: 1. Km to miles 2. Miles to km Your option: """))
print(km2miles(num))
success = True
else:
raise ValueError
except ValueError:
INPUT TestScores[Counter]
NEXT Counter
TestScores = []
=[47,56,12,…]
FOR CounterX0 TO 9
FOR CounterY 0 TO 1
INPUT “TestScores(CounterX,CounterY”)
NEXT CounterY
NEXT CounterX
MyList=[]
Print(MyList)
FOR CounterX0 TO 9
FOR CounterY 0 TO 1
INPUT “TestScores(CounterX,CounterY”)
NEXT CounterY
NEXT CounterX
- Totalling
- Counting
Totalling
Being able to to find the largest and smallest values in a data set is another common technique used in
algorithms
Following on from the totaling method we looked at earlier, it is also very common to calculate the
average (mean) of a set of values
- Variable declared outside of subroutines (procedures and functions) are global variables
- Global variables exist in memory for the entire time the program is running
- Global variables are accessible from any subroutine, but this is considered bad practice and should be
avoided
Drawbacks:
- Conflicts with variables that share the same name in other parts of the program makes writing
programs in teams and testing more difficult.
- Memory inefficient because the variables exist (and take up space In memory) while the program is in
use
It’s is better to pass in copies of global variables to use as parameters when calling subroutines
Routines: Ready complied and tested programs that can be run when needed
Some programming in the Windows operating system can call Dynamic Link Libraries (DLL)
Benefits:
- Quick and easy to use and hook into your own code
- Pre-tested, so you can be relatively sure they are already free from errors
Drawbacks:
- You have to trust the developers will continue to maintain the library
MOD: Value = 10 % 3
Import random
Value = random()
Value 1 1
Value 2 3
Value 3 6.97
Print(A%B)
Print(A//B)
import random:
print(random(randint.(100 , 300))
import random
a = random.randint(100,300)
b = random.randint (100,300)
print (a%b)
print (a//b)
LINEAR SEARCH
Starting from the beginning of a data set, each item is needed to checked in turn to see if it is the one
being searched for
A linear search:
Index 0
Found False
IF items[index] = item_to_find
THEN
Found True
ELSE
Index False
ENDIF
ENDWHILE
IF found True
THEN
RETURN “Item found at position”, index
ELSE
ENDIF
ENDFUNCTION
Bubble sort
- Compares each item with the next and swaps them if they are put in order – in effect bubbling the
largest (or smallest) item up to the end of the list
FUNCTION bubbleSort(items)
DECLARE n: INTEGER
DECLARE swapped: BOOLEAN
N items, length
Swapped True
Swapped False
Nn–1
FOR index 0 TO n – 1
THEN
Swap(items[index], items[index+1]
Swapped True
ENDIF
NEXT index
ENDWHILE
RETURN index
ENDFUNCTION
TRACE TABLE
Trading execution: A vital skill for understanding program flow and testing the accuracy of an algorithm
for logic
It involves examining a printed extract of program code and running thorough the program
- Take each line at a time and write the current state of each variable in a trace table
- Each variable present in the program should have its own column in the trace table
MAINTAINABILITY
To make your code as easy to read and maintain as possible, make sure you use:
- Descriptive variable names, explaining each variable’s purpose with a comment when it is declared
- Structure code
CLOSEFILE FileA.txt
CLOSEFILE FileB.txt
- Set a Boolean variable to false to indicate the end of file has not been reached
- While the end_of_file flag is false and the search item has not been found
- If the data matches what is being searched for, assign the data to variables or output
- Check if the end of the file has been reached and if it has, set the Boolean variable to true
Hybrid paper:
- Programming concepts:
- Sequence
- Selection
- Iteration
- Totalling
- Counting
- Writing pseudocode algorithms for a giving scenario using iteration and selection
- Arrays
Boolean Expression E = (A OR B) OR C
Shutdown conditions:
S = 0 AND T = 1
S = 1 AND W = 1
T = 0 AND W = 1
CPU: An electronic device that takes input, processes data and delivers output.
What is a microprocessor?
As with many areas of computer science, processing involves different terms that mean very similar
thing.
- Microprocessor
The terms CPU and microprocessor essentially mean the same thing
Control unit:
- Coordinates and communicates with all parts of the CPU (orange lines).
- It could be the next instruction in a sequence of instruction s or the address to jump to if the current
instructions us a command to jump or branch – this would be copied from the current instruction
counter
- Hold the address of the memory location that data or an instruction us to be fetched from OR written
to
- Sends
- All data to and from memory must travel down the data bus and pass through the MDR.
Opcode What to do?
+ ADD
+ SUBTRACT
+ MULTIPLY
+ DIVIDE
+ Comparison
+ AND
+ OR
+ NOT
+ XOR
Accumulator (ACC):
- The results of calculations carried out by the ALU can be temporarily stored here
Buses:
Address bus: Carries memory addresses that identify where data is being read from or written to.
Data bus: Carries the binary 1s and 0s that make up the actual information being transmitted around the
CPU/computer.
- Control bus: Carries commands and control signals to and from every other components of the
CPU/computer
- Control unit (CU): Sends signals to control how data moves around the CPU
- Buses: A collection of wires through which data and instruction transmitted from one component to
another
- Address bus: Unidirectional – carries the addresses that data needs to be written to or read from
- Control bus: Bidirectional – carries command and control signals telling components when they should
be receiving reads, writes, etc.
- Registers: Tiny, super-fast pieces or on-board memory inside the CPU, each with a very specific
purpose.
+ Program counter –
Key characteristics:
- Control unit
Fetch stage: The program counter is checked for the memory address of the next instruction to be
executed.
The memory address register(MAR) fetches the instruction from the main memory (RAM) and brings it
into the memory data register
1b.
Control bus: carries command and control signals telling components when they should be receiving
reads, writes, etc.
Address bus: carries the addresses that data needs to be written to or read from.
1c.
- Increasing bus width (data and address buses) increases the performance and speed of a computer
system
1. fetches
4. MAR
5. address bus
6. MDR
7. decoded
8. executed
9. control signals
11. ALU
12. ACC
The purpose of the CPU is to fetch, decode and execute instructions – it does this billions of times a
second.
Fetch:
1. The program counter is checked for the address of the next instructions to be executed
2. The contents of the program counter are copied into the memory address register
3. The program counter is incremented
4. The control unit sends a memory read request to main memory down the control bus
5. The address is sent down the address bus from the memory address register to main memory
6. The contents of main memory are sent down the data bus into the memory data register
7. The contents of the memory data register are copied into the current instruction register
Decode:
8. The instruction in the current instruction register is inspected and decoded to work out what
needs to be done.
Execute:
Secondary storage: Holds the operating system, programs and data when they are not in use
Faster access
Secondary:
Non-volatile
Slower access
- Non-volatile
- Volatile
+ When a computer system first receives power, there are no instructions in the CPU
+ The system needs to load the operating system so it can start functioning
+ However the operating system is stored on permanent secondary storage – the hard drive
+ A set of intitial startup instructions called the bootstrap is placed on the ROM during manufacture
+ ROM is non-volatile, which means that the data its contains is retained when the computer is powered
off
+ The first instruction in the bootstrap tells the computer to perform a power on self-test (POST)
+ As the computer is now aware of the hard drive, it can load the operating system into RAM
Primary storage: Any storage that can be directly access by the CPU – this includes:
- Random access memory (RAM)
- Read-only memory (ROM)
This type of storage holds the data and instructions that the CPU needs to access while the computer is
running. The CPU can access data from primary storage much faster than secondary storage
RAM:
Types of data:
ROM:
- Read-only
Q1. RAM - Holds program and data currently in use by the CPU
Q2.
RAM used to store data, files, programs, part of OS currently in use, an increase in the amount of ROM
has no effect on computer performance
RAM: used by both OS and applications software, when phone switched on, it pulls OS and app data
from solid state memory to allow it to function; user’s data
UNIT 1: Sound representation, image representation, file size calculations in gibibyte, units conversion,
data compression, run-length encoding, binary shift, two complements
UNIT 2: everything, identify key-terms with descriptions from unit 2, data packets
UNIT 10: Logic circuits, truth table, trace table, identify errors in algorithms, functions of CPU
components, fetch-decode-execute.
Virtual memory:
- Virtual memory is needed when there is not enough physical RAM available to store open programs
- Programs are transferred out to virtual memory from RAM when they are not currently being executed
- Programs are transferred back to RAM from virtual memory when they are needed
Cloud storage:
- With the ever-increasing bandwidth capabilities of fibre, optic and wireless 4G and 5G, we are
increasingly turning to cloud storage.
- The concept of storing and retrieving data virtually via the internet instead of a local storage device.
Advantages:
Disadvantages:
- can be expensive
All files kept in cloud storage are still stored on physical storage media in a remote location
Cloud storage warehouses often have thousands of servers containing hard drives
2a. Cloud storage: The concept of storing and retrieving data virtually via the internet instead of a local
storage device.
2b.
- Virtual memory is needed when there is not enough physical RAM available to store open programs
- Programs are transferred out to virtual memory from RAM when they are not currently being executed
- Programs are transferred back to RAM from virtual memory when they are needed
3a.
RAM:
- volatile memory
ROM:
- non-volatile memory
- always used to store BIOS and other data needed to start up.
3b.
RAM:
5b.
- they are considerably lighter (which makes them suitable for laptops)
5c. The longevity of the technology (although this is becoming less of an issue). Most solid state storage
devices are conservatively rated at only 20GB of write operations per day over a three-year period
EMBEDDED SYSTEMS
- Hospital instruments
- Digital clocks
- Small size
These benefits come at the cost of limited processing resources, making them more difficult to program
and interact with.
Embedded system are dedicated to a specific task – this means design egineers can optimise the system
to:
Embedded system: A computer system with a dedicated system within a larger mechanical system
- Small size
- Traffic lights
- Domestic appliances
- Factory equipment
- Factory equipment
- Hospital equipment
Tyres
Weather conditions
Aerodynamics
Clock:
Cache size:
- Temporary storage of data and instructions being read to and written from
Number of cores:
- A quad core processor would have four separate processing units, each with its own:
+ Registers
+ ALU
+ Accumulator
+ Control unit
- CPUs with multiple cores have more power to run multiple programs at the same time.
- Doubling the number of cores doesn’t simply double the overall speed
Exercise 3.2
1a. Clock:
Cache size:
- Temporary storage of data and instructions being read to and written from
Number of cores:
- A quad core processor would have four separate processing units, each with its own:
+ Registers
+ ALU
+ Accumulator
+ Control unit
- CPUs with multiple cores have more power to run multiple programs at the same time.
- Doubling the number of cores doesn’t simply double the overall speed
Increasing the width of the address bus and width of the data bus
Use of larger cache memories (uses static RAM) which have faster data access time than normal RAM
(which is dynamic)
Using dual core or quad core processors; but doubling number of cores doesn’t double processor
performance since the CPU needs to communicate with each core which uses up time.
1b. Every type of processor has its own specific lists of commands that it can understand, called an
instruction set.
Each operation is made up of an opcode (which indorms the CPU about what operation needs to be
done) and an operand (data which needs to be acted on/register)
Instruction sets are low level language instructions which instruct the microprocessor how to carry out
the sequence
- Data from satellites, which gives the location of three or four satellites together with very accurate
timings
- Sat Nav computers uses satellite data to calculate the position of a car on the stored maps
- Use of satellite or cellular network used to download the latest amp updates/software updates
- If the Sat Nav is a portable unit, it can be connected to a computer via network
- Ask people to explain why the artist might have done something
- design a postcard
a. Aid to Scouting
b. On Brownea Island
c. Chile
d. Rosebuds
e. two thirds
f. Indonesia
j. France
l.
- Help young people play useful roles in society applies equally to girls and boys