Copy of as Programming Notes June 25.PDF
Copy of as Programming Notes June 25.PDF
Programming
Notes
Instagram: @megztechteam 1
Chapter 12
Algorithm design &
Problem Solving
GZ
ME
Structured English A subset of the English language that consists of command statements used to
describe an algorithm
Pseudocode A way of using keywords and identifiers to describe an algorithm without following
the syntax of a particular programming language
Flowchart Shapes linked together to represent the sequential steps of an algorithm
In computer science, when writing algorithms, we use four basic types of constructs:
Assignment – Sequence – Selection – Repetition
GZ
Assignment:
Data Structures (Variable - Constant - Array)
ME
● Variable: A named storage location in a program for a data value that has an
identifier.
Example: The value of a running total.
● Constant: A named data location in a program for a value that does not change when
the program runs.
Example: The value of the pi (π).
● Array: A store (list) of data values that are all related & of the same data type
VariableName expression
VariableName: the name given to the variable by the programmer.
expression: the data that is held in the variable’s memory location.
ParkEntryCost 50 // Constant --- 2 backslashes before each new comment line
● CHAR: A single character; Delimited by single quotes e.g. ꞌxꞌ, ꞌCꞌ, ꞌ@ꞌ
● STRING: A sequence of zero or more characters; Delimited by double quotes. e.g.
"This is a string".
A string may contain no characters (i.e. the empty string) "".
● BOOLEAN: The logical values TRUE and FALSE.
● DATE: A valid calendar date; this will normally be written in the format dd/mm/yyyy.
However, it is good practice to state explicitly that this value is of data type DATE and
to explain the format (as the convention for representing dates varies across the
world).
Arithmetic operations
● + Addition
● - Subtraction
GZ
● * Multiplication
● / Division
● ^ Power (2^3 = 8)
ME
● INT
The predefined function INT gives the rounded down integer value of the given
number, e.g. y = INT (3.8) gives the value y = 3.
● MOD
The predefined function MOD gives the value of the remainder, for example, Y ← 10
MOD 3 gives the value Y = 1
● DIV
The predefined function DIV gives the integer result of the division, e.g.
Y = 10 DIV 3 gives the value Y = 3
Care should be taken with the division operation: the resulting value should be of data type
REAL, even if the operands are integers.
Multiplication and division have higher precedence over addition and subtraction (this is the
normal mathematical convention). However, it is good practice to make the order of
operations in complex expressions explicit by using parentheses.
Relational operations
Logic operators
The only logic operators (also called relational operators) used are: AND, OR and NOT.
The operands and the results of these operations are always of data type BOOLEAN.
In complex expressions, it is advisable to use parentheses to make the order of operations
GZ
explicit.
Sequence
Sequence: It is the concept of one statement being executed after another.
enter = input = given = read
calculate = output = print = find = determine
Practicing Algorithms
11. Write an algorithm that takes as input two numbers and swaps the values of these
numbers.
IF…THEN…ELSE…ENDIF
CASE…OF…OTHERWISE…ENDCASE
Example 1:
Example 2:
Example 3:
DECLARE MenuNumber : INTEGER
INPUT MenuNumber
CASE MenuNumber OF
1: OUTPUT “Salad”
2: OUTPUT “Chicken”
3: OUTPUT “Orange Juice”
OTHERWISE OUTPUT “Your order is not in the menu.”
ENDCASE
Example 4:
DECLARE Grade : INTEGER
INPUT Grade
CASE Grade OF
"A": OUTPUT "Excellent"
"B": OUTPUT "Good"
"C": OUTPUT "Average"
OTHERWISE
OUTPUT "Improvement is needed"
GZ
ENDCASE
Example 6:
GZ
IF…THEN…ELSE…ENDIF CASE…OF…OTHERWISE…ENDCASE
Used when we have a range of values Used when we have specific discrete values
A condition that can be true or false (only A choice between several different values
2 options) (more than 2 of values)
Checking for a condition that may be
complex
ME
Example 1: FOR
DECLARE Total : INTEGER
DECLARE Number : INTEGER
Total 0
FOR Counter 1 TO 4 STEP 1 // The loop will iterate 4 times
and increment the counter by 1
each time
OUTPUT “Type in a number” // This is called prompt.
INPUT Number
Total Total + Number
GZ
ENDFOR
OUTPUT Total
Example 2: WHILE
ME
Example 3: REPEAT
Practicing Algorithms:
1. Write an algorithm that inputs 100 numbers.
2. Write an algorithm that inputs 100 numbers and prints their total
3. Write an algorithm that inputs 100 numbers and prints their total and average.
4. Write an algorithm that inputs 100 numbers and prints their product.
5. Write an algorithm that inputs 100 numbers and prints out the largest number.
6. Write an algorithm that inputs 100 numbers and prints out the smallest number.
7. Write an algorithm that inputs 100 numbers and prints out how many numbers are
greater than 20.
8. Write an algorithm that inputs 100 numbers and prints out the total of numbers
greater than 20.
9. Write an algorithm that inputs 100 numbers and prints out the average of numbers
that are greater than 20.
10.Write an algorithm that inputs 100 numbers and prints out how many numbers are
negative.
11.Write an algorithm that inputs 100 numbers and prints the product of the positive
numbers only.
the process ends when the user enters -1 using REPEAT loop.
3. Write an algorithm that inputs some numbers and prints how many numbers are
negative, the process ends when the user enters 0.
4. Write an algorithm that inputs some numbers and prints the product of the positive
numbers only, the process ends when the product is greater than 70.
GZ
ME
Validation Functions:
1. Range check: (Number)
GZ
ME
SEARCH
FIND
- Indentation
- Capitalization of keywords
- Comments
- White space
GZ
ME
GZ
ME
Arrays (1D-2D)
Array: A store (list) of data values that are all related & of the same data type.
⮚ Once we have defined the size of the array, it cannot be changed.
⮚ All the data stored in the array should be of the same data type.
(INTEGER/REAL/CHAR/STRING/BOOLEAN…………….)
⮚ Once we have created an array, we can write data to the array and read data from it.
⮚ Element is an individual data location in an array.
GZ
Given the following Array:
ME
Writing to an Array:
Practicing Algorithms:
1. Write an algorithm that inputs 100 numbers in an array called ListA using a FOR loop.
2. Write an algorithm that outputs the total of 100 numbers stored in an array called
ListA.
GZ
3. Write an algorithm that outputs the total and average of 100 numbers stored in an
array called ListA.
4. Write an algorithm that outputs the product of 100 numbers stored in an array
called ListA.
5. Write an algorithm that outputs the largest number of 100 numbers stored in an
ME
14. Write an algorithm that inputs 100 numbers inside an array called ListA and outputs the
product of the positive numbers only (WHILE Loop)
15. Write an algorithm that inputs 100 numbers inside an array called ListA and outputs the
average of numbers less than 30. Validate each number input to be positive (REPEAT Loop)
Linear Search: checking each element of an array in turn for a required value.
GZ
ME
GZ
ME
Practicing Algorithms:
1. Write an algorithm that inputs a number and outputs whether this number is found
inside an array called ListA or not, array ListA stores 50 numbers.
Bubble Sort: a sort method where adjacent pairs of values are compared & swapped.
GZ
ME
GZ
ME
GZ
ME
GZ
ME
GZ
ME
Practicing Algorithms:
1. Write an algorithm that sorts an array called ListA ascendingly. ListA stores 100
numbers.
2D arrays
GZ
ME
Practicing Algorithms:
1. Write an algorithm that prints the values inside the 2D array ListA.
2. Write an algorithm that prints the total of values stored inside the 2D array ListA.
3. Write an algorithm that prints the average of marks for each student inside the 2D
array ListA.
4. Write an algorithm that prints the total of marks for each student.
5. Write an algorithm that inputs values to a 2D array called ListA>
GZ
ME
Chapter 13
Procedures, Functions,
Structure Charts and File
Handling
GZ
ME
Terminology
Different programming languages use different terminology for their subroutines
Another method of developing a solution is to decompose the problem into sub-tasks. Each
sub-task can be considered as a 'module' that is refined separately. Modules are procedures and
functions. A procedure groups together a number of steps and gives them a name (an
identifier). We can use this identifier when we want to refer to this group of steps. When we
want to perform the steps in a procedure we call the procedure by its name.
Procedure: is a set of programming statements grouped together under a single name
that can be called to perform a task at any point in a program.
GZ
ME
These are useful subroutines written by other programmers and made available in module
libraries. The most-used ones are usually in the system library, so are available without having
to explicitly import them. You can write your own functions. Any function you have written
can be used in another program if you build up your own module library. A function is used as
part of an expression. When program execution gets to the statement that includes a function
call as part of the expression, the function is executed. The value returned from this function
call is then used in the expression. When writing your own function, ensure you always return
a value as part of the statements that make up the function (the function body). You can have
more than one RETURN statement if there are different paths through the function body.
Function: is a set of programming statements grouped together under a single name
that can be called to perform a task at any point in a program. In contrast to a procedure,
a function will return a value back to the main program.
A procedure is a set of programming statements grouped together under a single name that
can be called to perform a task at any point in a program.
A function is a set of programming statements grouped together under a single name that can
be called to perform a task at any point in a program. In contrast to a procedure, a function will
return a value back to the main program.
Parameters are the variables that store the values of the arguments passed to a procedure or
function. Some but not all procedures and functions will have parameters.
Return value: the value replacing the function call used in the expression.
Just like with a procedure, a function call must match the function definition. When a function
is defined with parameters, the arguments in the function call should match the parameters in
the procedure definition. For IGCSE Computer Science the number of parameters used is
limited to two.
GZ
The variable Number is not accessible in the main program. Python's variables are local
unless declared to be global.
Local variable: a variable that is only accessible within the module in which it is declared.
Global variable: a variable that is accessible from all modules.
ME
A global variable is available in any part of the program code. It is good programming practice
to declare a variable that is only used within a subroutine as a local variable. In Python, every
variable is local, unless it is overridden with a global declaration.
Stepwise refinement
Modules
GZ
ME
GZ
ME
Built-in functions
Programming environments provide many built- in functions. Some of them are always
available to use; some need to be imported from specialist module libraries.
GZ
ME
LENGTH
LENGTH ( “CS” ) → 2
LENGTH ( “Computer” ) → 8
LENGTH ( 4 ) → ERROR
UCASE
GZ
UCASE ( “ Happy” ) → HAPPY
Returns same string with all letters in uppercase
LCASE
LCASE ( “ Happy” ) → happy
ME
SUBSTRING
SUBSTRING ( “Computer” , 2 , 3 ) → omp
⬇ ⬇ ⬇
String Starting Number of characters
Index
SUBSTRING ( “ Computer Science” , 1 , 4 ) → Comp
--------------------------------------------------------------------------------
Arithmetic functions
Numbers
DIV (---,---)
ROUND (---,---)
RANDOM ( )
INT()
DIV(10 , 3) DIV(2.8 , 1)
10 DIV 3 2.8 DIV 1
9/3 2/1
3 2
MOD(10 , 3) MOD(7 , 4)
10 MOD 3 7 MOD 4
10 – 9 7–4
1 3
ROUND(5.694 , 0)
ME
INT(5.694)
5
RANDOM
X ← RANDOM ( )
Returns a random number between 0 & 1 inclusive
GZ
ME
GZ
ME
User-defined Functions
Passing parameters to functions
Argument: the actual input expression or value with which the subroutine is being called.
Parameter: the variable(s) used inside a subroutine which will take values passed into a
subroutine.
Subroutine interface: the parameters being passed between the subroutine and the calling
program.
GZ
Function / Procedure header: the first line of a function or procedure definition showing the
identifier and parameter list.
of the variable is passed into the subroutine. The value of the variable in the calling program is
not affected by what happens in the subroutine.
For procedures, a parameter can be passed by reference. At call time, the argument must be a
variable. A pointer to the memory location of that variable is passed into the procedure. Any
changes that are applied to the variable's contents will be effective outside the procedure in the
calling program/module.
Note that neither of these methods of parameter passing applies to Python. In Python, the
method is called pass by object reference. This is basically an object-oriented way of passing
parameters and is beyond the scope of this chapter. The important point is to understand how
to program in Python to get the desired effect.
GZ
Python does not have a facility to pass parameters by reference. Instead the subroutine behaves
as a function and returns multiple values. Note the order of the variables as they receive these
values in the main part of the program.
Summary
ME
Passing by Value: Copy of the current value of the variable is passed into the subroutine.
The value of the variable in the calling program is not affected by what happens in the
subroutine.
Passing by reference: A pointer to the memory location of the variable is passed into the
procedure. Any changes that are applied to the variable’s contents will be effective
outside the procedure in the calling program/module.
Practicing Algorithms:
1. Write a procedure called Average that takes 2 integers as parameters and
prints their average.
2. Write a programming statement to call the Average procedure
3. Write a function called Avg that takes 2 integers as parameters and
returns their average.
4. Write a programming statement to call the Avg function and assign the
returned value to a variable called x.
5. Write a procedure called Maximum that takes 3 integers as parameters
and prints the largest number.
GZ
6. Write a programming statement to call the Maximum procedure
7. Write a function called Highest that takes 3 integers as parameters and
returns the largest number.
8. Write a programming statement to call the Highest function and assign
ME
Structure charts
An alternative approach to modular design is to choose the sub-tasks and then construct a
structure chart to show the interrelations between the modules. Each box of the structure chart
represents a module. Each level is a refinement of the level above.
A structure chart also shows the interface between modules, the variables. These variables are
referred to as 'parameters'. A parameter supplying a value to a lower-level module is shown
as a downwards pointing arrow. A parameter supplying a new value to the module at the next
higher level is shown as an upward pointing arrow.
The next figure shows a structure chart for a module that calculates the average of two numbers.
The top-level box is the name of the module, which is refined into the three subtasks of Level
1. The input numbers (parameters Number1 and Number2) are passed into the 'Calculate
GZ
Average' sub-task and then the Average parameter is passed into the 'OUTPUT Average' sub-
task. The arrows show how the parameters are passed between the modules. This parameter
passing is known as the 'interface'.
ME
GZ
ME
GZ
ME
Structure Chart
MODULE NumberGuessingGame
SecretNumber = GenerateSecretNumber()
GZ
Guess = InputGuess()
CALL OutputMessage(Guess, SecretNumber)
ENDMODULE
ENDFUNCTION
MODULE FindMaximum
Max = 0
REPEAT
Number = GetNumber()
GZ
Changed = isLarger(Max, Number)
IF Changed THEN
CALL OutputChange()
ENDIF
UNTIL Number < 0
CALL OutputMax(Max)
ENDMODULE
ME
PROCEDURE OutputChange()
OUTPUT “This Value is currently the largest“
ENDPROCEDURE
File Handling
GZ
ME
Write an algorithm that opens a file that is stored and reads the first line in
the file then outputs the length of characters.
GZ
DECLARE TextLine : STRING
OPENFILE “MyFile.txt” FOR READ
READFILE “MyFile.txt” , TextLine
OUTPUT LENGTH(TextLine)
CLOSEFILE “MyFile.txt”
ME
GZ
ME
Practicing Algorithms:
1. Write an algorithm to count and output the number of lines inside this text
file. Assume the text file is called “FileA.txt”.
2. Write an algorithm to count and output the number of ‘a’ characters in
each line, as well as the number of ‘a’ characters in the entire text file.
Assume the text file is called “FileA.txt”.
3. Write an algorithm that reads all the words in “FileA.txt” and writes the
words that contain letter ‘A’ or ‘a’ in a new file called “FileB.txt”. Assume
each line in the text file has one word.
4. Write an algorithm that copies all the words that start with letter ‘M’ from
“FileA.txt” to “FileB.txt”. Assume each line has more than one word.
GZ
ME
GZ
ME
Chapter 14
Data Types & Structures
Primitive data types are those variables that can be defined simply by commands built
into the programming language. Primitive data types are also known as atomic data
GZ
types. In Computer Science a whole number is referred to as an INTEGER and a number
with a decimal point is referred to as a REAL. Conditions are either TRUE or FALSE. These
are logical values known as BOOLEAN. Sometimes we may want to store a single character;
this is referred to as a CHAR. A value that will always be a whole number should be defined
to be of type INTEGER, such as when counting the iterations of a loop.
ME
2. Records:
A record is a user-defined data type. The record type includes several variables with
different data types. It is known as a composite type.
1. Record Type Declaration:
TYPE <TypeIdentifier>
DECLARE <field identifier 1> : <data type>
DECLARE <field identifier 2> : <data type>
.
.
.
ENDTYPE
Example:
TYPE Student
DECLARE Name: STRING
DECLARE ID: STRING
DECLARE Age: INTEGER
DECLARE DateOfBirth: DATE
ENDTYPE
Person.ID “123456789”
Person.Age 16
Person.DateOfBirth 4/4/2004
3. Arrays
An array is an ordered set of data values of the same data types. The array elements
are accessed using the array index. Arrays can be 1D or 2D (matrix).
Array index: row or column number of an individual array element
Upper bound: the highest number index of an array dimension
Lower bound: the smallest number index of an array dimension
1. 1D Array Declaration:
DECLARE <arrayIdentifier> : ARRAY[<lowerBound>:<upperBound>] OF
<dataType>
Example:
DECLARE Letters: ARRAY [1:10] OF CHAR // 10 CHAR elements
DELARE Age: ARRAY [0:5] OF INTEGER // 6 INTEGER elements
2. Accessing 1D Array Elements:
<arrayIdentifier>[index]
Example:
Letters[5]
Age[0]
● The nth element within the array MyList is referred to as MyList[n]
GZ
ME
● When an element is removed, all other elements are moved forward and
the EndOfQueuePointer points to the new last element of the queue.
● When an element is added/enqueued, the EndOfQueuePointer will be
incremented.
● EndOfQueuePointer has value -1 when the queue is empty.
GZ
2. Circular Queue:
In the circular queue, the FrontOfQueuePointer points to the first element in
the queue regardless its position in the array (array index does not have to be
0). Also, the EndOfQueuePointer points to the last element in the queue.
When an element is removed, only FrontOfQueuePointer and
EndOfQueuePointer adjust their positions, but the array elements do not move
ME
forward.
Advantage: Less moving of data elements 🡪 more efficient.
Linked List is another way to store data rather than using an array. Unlike the
array, the elements/data of a linked list do not need to be stored in consecutive
memory locations. Instead, several elements will be linked using pointers to
show their order in a linked list. An element of a linked list is known as a
node. It consists of the data value and a pointer.
Node: An element of a linked list that consists of several data items and a
pointer.
Pointer: A variable that stores the address of the node it points to.
Null pointer: A pointer that does not point at anything. It is usually
represented by Φ.
Start pointer: A variable that stores the address of the first element of a
linked list.
Below are the diagrams of some operations of the linked list:
1.1. Inserting a new node at the beginning of a linked list:
GZ
ME
1.3. Inserting a new node within two existing nodes in a linked list:
To implement a linked list using arrays, we need two 1D arrays. The first
array, Data, stores the data values of the linked list while the second array,
Pointer, stores the pointers. The elements in both arrays at a certain index
represents a node. The null pointer in the Pointer array has the value -1.
Below are the diagrams of the operations of the linked list implemented by 1D
arrays:
1.1. Inserting a new node at the beginning of a linked list:
GZ
ME
1.3. Inserting a new node within two existing nodes in a linked list:
GZ
ME
It is important to be able to find and access unused nodes. A free list can be
used to link all unused nodes.
GZ
Free List: The linked list/part of the linked list that consists of unused/empty
nodes.
When declaring any linked list, it is initially empty (free list). This means that
ME
the StartPointer is -1. The FreeListPointer is another pointer that points to the
first empty slot in the list and all nodes are linked together to form the free list
as shown in the figure.
GZ
ME
Chapter 15
Software Development
GZ
ME
Analysis
● Discuss the program requirements with the customer.
● A ‘requirements specification’ (document) is drawn up.
● Investigate the issues and the current system if there is one. The problem needs to be
defined clearly and precisely.
● Planning a solution. Sometimes there is more than one solution. You need to decide
which is the most appropriate.
● Documentation related to current system such as ER diagram or DFD or feasibility
study
GZ
● Decide how to solve the problem:
o bottom-up: start with a small sub-problem and then build on this
o top-down: stepwise refinement using pseudocode, flowcharts or structure
charts.
Design
● Plan your algorithm by drawing a flowchart or writing pseudocode.
ME
When the program works and is being used, issues might arise that require changes. This is
known as Maintenance.
The program development life cycle follows the defined stages of analysis, design, coding
(implementation), testing and maintenance.
What are the Waterfall Model’s principals?
GZ
ME
● The arrows going down represent the fact that the results from one stage are input into
the next stage.
● The arrows leading back up to an earlier stage reflect the fact that often more work is
required at an earlier stage to complete the current stage.
● Each stage is fully carried out before the next.
●
very early stage of development, which makes development projects can
it easier to find functional or design flaws. benefit because it is hard to
Finding issues at an early stage of development break a small software system
means corrective measures can be taken more into further small serviceable
quickly. modules.
● Some working functionality can be developed ● More resources may be
quickly and early in the life cycle. required.
● Results are obtained early and periodically. ● Design issues might arise
● Parallel development can be planned. because not all requirements are
● Progress can be measured. gathered at the beginning of the
● Less costly to change the scope/requirements. entire life cycle.
● Testing and debugging of a smaller subset of ● Defining increments may
program is easy. require definition of the
● Risks are identified and resolved during complete system.
iteration.
● Easier to manage risk – high-risk part is done
first.
● With every increment, operational product is
delivered.
● Issues, challenges and risks identified from
each increment can be utilised/applied to the
next increment.
table.
GZ
ME
GZ
ME
GZ
ME
Testing Methods
● Stub Method
o Test some procedures/modules before you have implemented all the other
procedures/modules.
o write a ‘stub’ (simpler version) for each called procedure/module.
o The stub will return an expected value or output a message showing that it has
been called.
● Black-box testing
o Comparing expected results with actual results when a program is run.
o program should be tested by people who do not see the program code and
don’t know how the solution was coded.
o Such program testers will look at the program specification to see what the
program is meant to do, devise test data and work out expected results.
o Test Data: Carefully chosen values that will test a program
o Test Data usually consists of Normal values, Boundary values,
Abnormal/Erroneous values.
● White Box Testing
o Testing every path in the program.
● Dry-running an algorithm (Tracing)
o the process of checking the execution of an algorithm or program by
recording variable values in a trace table
o Trace Table: a table with a column for each variable that records their
GZ
changing value.
● Integration testing: individually tested modules are combined into one program and
tested to ensure the modules interact correctly
● Alpha testing: testing of software in-house by dedicated testers
● Acceptance testing: testing of software by customers before sign-off
● Beta Testing: testing of software by a limited number of potential users before
ME
general release. The beta testers will check if the program works as expected in the
real world and give back feedback that should be addressed before selling the
software.
GZ
● To test the algorithm, construct a trace table with one column for each variable
used in the algorithm and also for the condition Guess > SecretNumber
● Now carefully look at each step of the algorithm and record what happens. Note
that we do not tend to write down values that don't change. Here SecretNumber
ME
does not change after the initial assignment, so the column is left blank in
subsequent rows.
● We only make an entry in a cell when an assignment occurs. Values remain in
variables until they are overwritten. So a blank cell means that the value from
the previous entry remains.
● It is important to start filling in a new row in the trace table for each iteration
(each time round the loop).
GZ
ME
GZ
ME
GZ
ME
GZ
ME