0% found this document useful (0 votes)
22 views77 pages

Key+Points+Paper+2 +CS+Revision

Uploaded by

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

Key+Points+Paper+2 +CS+Revision

Uploaded by

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

KNOWLEDGE

ORGANISERS
COMP 2 REVISION: COMPUTATIONAL THINKING, ALGORITHMS &
PROGRAMMING

1
Revise on the following PLC’s for Paper 2
2.1 Algorithms 1 Computational thinking: Decomposition/Abstraction/Computational Thinking
2.1 Algorithms 2 Standard searching algorithms: Binary and Linear
2.1 Algorithms 3 Standard sorting algorithms: Merge /Bubble/
2.1 Algorithms 4 How to produce algorithms using: Pseudocode/Flowcharts/Trace table
2.1 Algorithms 5 Interpret, correct or complete algorithms
2.2 Programming techniques 6 The use of variables, constants, operators, inputs, outputs and assignments
2.2 Programming techniques 7 The use of the three basic programming constructs: Sequence/Selection/Iteration

2.2 Programming techniques 8 The use of the three basic programming constructs: Iteration (count and condition controlled loops)
2.2 Programming techniques 9 The use of basic file handling operations: (Open, Read, Write, Close) / Arrays
2.2 Programming techniques 10 The use of SQL to search for data
2.2 Programming techniques 11 How to use sub programs (functions and procedures) to produce structured code
2.2 Programming techniques 12 The use of data types: Integer, Real, Boolean, Character & String, Casting
2.4 Computational logic 13 Simple logic diagrams using the operations AND, OR and NOT
2.4 Computational logic 14 Truth tables
Characteristics and purpose of different levels of programming language, including low level
15
2.5 Translators and facilities of languages languages/high level languages
Common tools and facilities available in an integrated development environment (IDE): Editors, Error
16
2.5 Translators and facilities of languages diagnostics, Run-time environment, Translators
2.5 Translators and facilities of languages 17 Translators : Compiler and Interpreter
3
2.1 – Algorithms - Computational Thinking KEY TERMS
What is Computational thinking?
Algorithm: Steps to provide a solution to a
problem, usually represented in flowcharts
3
Flowcharts
or pseudocode
The thought processes involved in Displays an algorithm in diagram form using
symbols and arrows to show to flow of
formulating a problem and its Decompose: Breaking down a large
problem into smaller sub-problems information
solution(s), so that a computer,
human or machine can effectively Abstraction: Representing 'real world' Pseudocode
carry out problems in a computer using variables and A structured use of English used to define the
symbols and removing unnecessary steps needed to solve a problem.
1 elements from the problem

Algorithmic Thinking: Identifying the steps


How do you think involved in solving a problem. WHILE TRUE:

computationally?
Structure diagram – a hierarchical diagram temp = “” 3
that shows how a problem is broken down
into sub-sections/sub-tasks IF temp > than 20c THEN
To effectively solve problems you need Open windows AND heaters OFF
to…. Sequence: Completing steps in the order ELSE
which they must happen Close windows AND
heaters ON
• Decompose
• Selection: Where a choice is made in a
Abstract TIME = “”
program depending on a condition or
• Algorithmic thinking IF TIME = 18.00 THEN
outcome
• Create algorithms Sprinklers on

1 Iteration: Act of repeating or lopping


ELSE

specific sections of code 2 Sprinklers off


Continue 4
BREAK
2.1 – Algorithms – 4. Flowcharts SUB
ROUTINE
START/STOP
Sequence that performs a specific task.
Always start and end with this You can use this within your flowchart
to show more detail in a specific section

INPUT/OUTPUT
PROCESS

Use when there is an input or output To do something in


required e.g. user inputs their name, the program e.g a
program displays their name calculation
Decision

Is No Flow lines – show


A>10 the flow of
? information in the
When a choice has to
be made in the algorithm
program 5
YES
2.1 – Algorithms – 5. Pseudocode The OCR Pseudocode guide has
more information if you wish to do
Here are some symbols to use more research.
Pseudocode uses English.
It mimics how your code may look Comparison operators
WHILE TRUE:
in the programming language BUT temp = “”
it DOESN’T have to be exact == Equal to
IF temp > than 20c THEN
!= Not equal to
Open windows AND heaters OFF
< Less than ELSE
Some useful terms you could <= Less than or equal to Close windows AND
use.  Greater than heaters ON

>= Greater than or equal to TIME = “”


START IF TIME = 18.00 THEN
Sprinklers on
IF Arithmetic Operators ELSE
ELIF Sprinklers off
ELSE + Add
Continue
BREAK
FOR
WHILE TRUE - Subtract This repeats, it reads the temp of a
/ Divide greenhouse. If greater than 20 degs then
ENDIF open windows and turn heaters off ELSE close
* Multiply
END MOD will return the remainder for the
windows and heaters on

It checks the time if the time is 6pm then turn


division sprinklers on otherwise keep sprinklers off
6
2.1 – Search Algorithms - Binary and Linear searches

7
2.1 – Sorting Algorithms – Bubble, Insertion & merge

8
9
11
Answer

12
2.2 Programming Techniques
Syntax Error
Constant An error in the rules/grammar of the language Eg missing colon / spelling mistake
Value STORED IN A MEMORY LOCATION that
never changes WITHIN A PROGRAM Logic Error
The program is written to do something other than what the programmer intended
Variable Eg Resetting only the first 9 elements in an array instead of all 10.
Value STORED IN MEMORY LOCATION that
Run Time Error:
can change WITHIN IN A PROGRAM More difficult to spot as it can run a program without reporting an error. E.g. runs but
Doesn’t give an output. Or the program hangs or Becomes inactive

Sequence: Completing steps in the order


which they must happen
Data Types Other Info
Real /Float
Selection: Where a choice is made in a Number with decimal Point Concatenate
program depending on a condition or Integer To join different data types together
outcome Number without a decimal Point
String # Comments
Iteration: Act of repeating or lopping Use these to add comments in to your code to
A series of characters/TEXT
explain what you have done
specific sections of code Character
Count controlled Iteration: A single letter or symbol
Validation: An computer check to
Repeats a set number of times Date/Time
Date and Time in any format
ensure that the data entered is sensible
Condition controlled: Repeats
Boolean and reasonable. It does not check the
until a condition is met or something in the
Yes no, true false value accuracy of data.
program changes 15
Developing algorithms using pseudocode
Unit 6 Algorithms

Selection
• An IF statement is a type of selection statement
• The next statement to be executed depends on
whether the condition being tested is TRUE or FALSE
hoursPerNight = int(input("How many hours a night
do
you sleep?"))
if hoursPerNight < 8 then
Execute this if TRUE
print("That’s not enough!")
else Execute this if FALSE
print("That’s plenty!")
endif
Developing algorithms using pseudocode
Unit 6 Algorithms

The switch/case statement


• The switch/case statement is used if there are several possible
options to be tested
switch optionChosen:
case 1:
print("You chose option 1") Execute if optionChosen is 1
case 2:
print("You chose option 2") Execute if optionChosen is 2
case 3:
print("You chose option 3") Execute if optionChosen is 3

default:
Execute if no
print("Please select a valid choice") cases match
endswitch
Python operations
Command Name Example Output MOD: will return the remainder
for the division. (Some programming
+ Addition 4+5 9
languages will use the % symbol for
- Subtraction 8-5 3 MOD).
* Multiplication 4*5 20
/ Division 19/3 6.3333
% Remainder 19%3 1
** Exponent 2**4 16

Do you remember order of operation that you learnt in maths?


multiplication * and division \ have higher order than addition + and subtraction -

Calculations are done from


left to right, UNLESS you
put in parentheses.
Pseudocode Algorithm Example.
Write an algorithm that takes a user’s mark = input(“Input mark”)
mark as input and outputs If mark < 50 then
print(“Fail”)
• “Pass” if they scored on, or over 50
elseif mark < 70 then
• “Merit if they scored on, or over 70 print (“Pass”)
• “Distinction” if they scored on, or over 90 elseif mark < 90 then
• or “Fail” if below 50 print (“Merit”)
else
print(“Distinction”)
endif
Iteration
• Iteration means repetition
• There are three types of iteration statement in most, but not all, imperative programming
languages such as Pascal, Visual Basic or Python.
• for … next [For loops are used when you have a block of code which you want to
repeat a fixed number of times. ]
• while …endwhile [A while loop statement in Python programming language
repeatedly executes a target statement as long as a given condition is true do …
until]

for i = 1 to 10 while (i != 11)


... ...
next i endwhile
Trace table

b)Rewrite the algorithm in OCR Exam Reference language


Answer
Exam Question 9
Exam Question 9 Ans
2.2 Programming Techniques

30
31
Writing to a file

Tells the program


Variable / Opens/create a file File name we want to “write”
file handler

Write
file = open("test1.txt", "w") Move to a
inside the
file.
file.write("Welcome\n") new line.

file.write("My Friend") Values/text


that will be
Closes
the file
file.close() inside the
file.
File Handling
Remember when using files you have to open them in either read, write or append mode.
You have to open the file, do your reading or writing, then close the file.

What does this code do?

What does this code do?

Does a Procedure or a Function return a value ? Underline which you think is correct
34
Procedures and Functions
Operator Operator

procedure hello(name)
print(“Hello “ + ) fill in the missing code == *
Endprocedure

!= /
function doubler(number) What is this part of the function
return double * 2 called
End function < -

> MOD

>= DIV

Name the operator Power of


Exam Question 5 ANS
Task 6
Answer
Generating random numbers
A typical method of generating random numbers might look
like this:

month:= getRandBetween(1,12)

number = random(1,10)
Syntax
• The exact structure of a random number generator will
vary between programming languages.

• Using the OCR Exam Reference Language you can


either state the first and last possible values
e.g. diceRoll = random(1,6)

• Or just the maximum value, if starting from 1


e.g. diceRoll = random(6)

• Note that the actual method for some languages


(e.g. Visual Basic) involves generating a real number
between 0 and 1, then multiplying to get a larger integer.
Activity 1
Design an algorithm to simulate two random dice rolls and
check if they the player has rolled a double.

Devise your own scoring system that will award players with
points based on their dice rolls.
Example
roll1 = random(1,6)
roll2 = random(1,6)

if roll1 == roll2 then


print(“Player rolled a double!”)
points = roll1 + roll2 + 10
else
print(“No double”)
points = roll1 + roll2
Generating random choices
• Not every random choice is going to be a number.

• In the game Rock, Paper, Scissors, the computer needs


to randomly choose which move to play.

• There are three choices to pick from, so we can generate


a random number between 1 and 3.
Example
choice:= random(1,3)
if choice = 1 then
cpuMove:= “Rock”
elseif choice = 2 then
cpuMove:= “Paper”
elseif choice = 3 then
cpuMove:= “Scissors”
Answer
STRUCTURED QUEARY LANGUAGE

Answer the following queries


'!=' means 'not equal'
Data Types and SQL
50
2.3 Robust Programs Data Validation techniques

Producing robust programs so that they are


defensive against hacks and attacks.

Data Validation: check to ensure that the data entered


is sensible and reasonable. It does not check the
accuracy of data.

Data Sanitisation: Trims or strips strings, removing


unwanted characters to make sure it contains only
permitted characters . E.g. Da%ve the % would be
removed.

Authentication: The process of verifying the identify of


a user or process

Maintainability : Updating code so that it is compatible Anticipating Misuse: Defensive program design will consider and anticipate
with current requirements misuse. Misuse may be in the form of a brute force attack on the program.
E.G Many programs and systems only allow a user to enter a password three
Comments: To help describe the code and structures or four times before it locks out the system.
in a program using #
Contingency Planning: Once a programmer has anticipated the misuse they can
Indentation: used to show the programs structure e.g. then plan for the these issues. For example: Limiting the number of logon
where selection or iteration or functions are used . attempts. Ensuring the code is robust in validating the data entered
51
2.3 Robust Programs Test data – When testing your programs it is important to use of
data to test and to create a test plan.
Iterative testing: This happens overtime and is repeated
throughout the development of the program

Final/terminal testing: is when the product is released


and real end users begin using it. Very often, end users
find things wrong with systems that the programmers
did not expect.

Syntax Errors: An error in the rules/grammar of the


language Eg missing colon / spelling mistake

Logic errors: The program is written to do something


other than what the programmer intended Eg Resetting
only the first 9 elements in an array instead of all 10.

Test Data: Something which has been specifically


identified for use in tests, typically of a computer
program

Example test plan

52
53
2.4 Computational logic Truth Tables: Display all possible
outcomes for that gate
Logic Gate: A building block of a digital circuit. They
perform logical functions in a circuit and use binary IN OUT
Not Gate 0 1
1 0
Inverts the input (0 becomes 1 and 1
becomes 0
A B Out
0 0 0
OR Gate
0 1 1
Wait for either inputs to be 1 for output to 1 0 1
be 1 1 1 1
A OR B

A B Out
AND Gate 0 0 0
Both inputs to be 1 for output to be 1 0 1 0
A AND B 1 0 0
1 1 154
2.4 Computational logic TRANSISTOR: A tiny switch that is activated by the
electronic signals it receives. The digits 1 and 0
used in binary reflect the on and off states of this.

Logic CIRCUIT: A combination of HINT: when completing the


different logic gates used to perform inputs in a truth table – don’t
more complex tasks forget to count up in binary, to How many rows do you need in a
make sure you have all possible truth Table?
inputs
A and B re inputs. There are 4 So for 1 input = 1 x 2 = 2
rows – starting from 0 make the For 2 inputs = 2 x 2 = 4
binary numbers 0,1,2,3.
Notation For 3 inputs = (2x2)x2 = 8
The symbols used to describe logic gates A B Out For 4 inputs = 2x2x2x2 = 16
And 0 0 0 0
V Or 1 0 1 0
2 1 0 0
3 1 1 1
EG. The notation below means – P = A
and b and not c. When you draw the
circuit the one in brackets goes first
Y = A B ( C)
C
55
Why is data represented in Binary in a
2.4 Computational logic computer system?:
• Binary is the representation of the
‘presence’ of electricity
An example logic circuit, with notations and truth table • If present or ‘on’ we use a: 1
A (BVC)
• If absent or ‘off’ we use a: 0
• We can use this idea to change 1 and 0
states through the use of logic gates
• Logic Gates take inputs and covert them to
an output
• The digit 1 or 0 is stored in transistors
which are in the processor.

Half Adder: A circuit to add two binary bits


together

Full Adder circuit: 2 half adders together.


This can add more than two binary bits
together and deal with carrying bits over
56
57
Selection
2.5 Translators and Facilities A condition is used to decide
executed
High Level Language (eg Python) How Instructions are stored in Binary. • if x = 1 then y = 3 else x whether
• Use Instructions are in Words code should be = 2
• Designed to be read by human programmers • The instruction consists of an operator/op
• Portable/translated for different machines code and an operand Sequence
PROS: Easy for humans to understand as written in English • both stored as bit patterns A list of instructions to be
CONS: Needs to be translated in to machine code so not as • (op code) from a given instruction set followed one after the other.
fast to execute • Each op code has a unique bit pattern Step by step

Why Use Binary.


• So that computers can be based on logic Iteration
Machine Code (Binary Code) (low level) circuits. code is executed repeatedly
• Instructions are in binary code Designed to be • (each part of the circuit) can be in one of two For I in range (10);
read/executed by the computer states Print (i)
• Specific to a particular machine • 0 and 1/true or false
PROS: Fast no need to translate already in binary, close to
CPU Translators
CONS: Difficult to read and understand for humans Interpreters:
Translates one line of HL code at a time…
 … and executes it
Assembly Language (low level)  … stops when it finds an error
• Low Level Language written in mnemonics that closely  … can be resumed
reflect the operations of the CPU Compilers:
• Eg LOAD Translates whole program of HL code at a time…
PROS: A bite easier to understand than binary as uses  … and executes it
mnemonics  … Optimise code
CONS: Still needs translating to machine code using an
Assembler: 58
Assembler translator
Translates Assembly language into machine code
The order of languages
Your computer only understands 1’s and 0’s, so how does your CPU understand a programming language like Python?

High level
Language
Low level
Language

Machine Code

Hardware
2.5 Translators and Facilities

TOOLS FOR PROGRAMMING


Source Code: The code the programmer writes
IDE (integrated Development Environment): A software application
that provides all the facilities to computer programmers for developing
programs. It normally consists of a source code editor, build automation
Object Code: code converted by the compiler
tools and a debugger so that it can be understood by the computer

Code Editor – edits program text, you can type our your source Executable Code: Files which contain
code here instructions in machine code. These
Syntax Checks – Highlights syntax errors instructions are carried out in the computer
hardware
Runtime Environment – allows programs to be run one line at a
time – helps test programs and locate errors. Programming Standards
Code should follow agreed conventions (EG Lowercase for
variable names, schemes to be followed).
Translator – Compiles or interprets the code
Language code is written in.
Libraries – Provides functions not included in core part of Functions used to tidy up repeated code.
programming languages (eg Random) Comments explain the code clearly.
Correct use of indentation.
Debugger – Helps to detect errors. Suggests what type of error it Useful identifiers (File names & Variable names)
is and what line it is on.
Code should follow agreed conventions
60
Compilers
• Compilers
• Translate entire source code all in one go into Machine Code
• Optimise code
• Used at the end of development (ready for shipping)
• Error Reports created along with Object Code
Interpreters
• Interpreters
• Translate and execute source code
• Line by Line, Statement by Statement
• Source code is checked for syntax – if correct, code is executed. If incorrect
interpreting is stopped.
• Used for development (aide debugging)
Integrated Development Environment (IDE)
• Integrated Development Environment (IDE)
1. Editor (for writing the code such as auto-correct, auto-indent)
2. Error Diagnostics (such as de-bug facilities to detect errors.)
3. Run-Time Environment (you can execute the program one step at a time)
4. Translators (This compiles or interprets the code).
5. Break point (Common debugging tool they stop the program on certain lines.
6. Code completion (assist programmers by intelligently identifying and inserting
common code components).
Advantage and disadvantage of Binary Search
Advantage and disadvantage of Linear Search
Advantage and disadvantage of Bubble Sort
Advantage and disadvantage of Insertion Sort
Advantage and disadvantage of Merge Sort

You might also like