Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Copy of as Programming Notes June 25.PDF

Uploaded by

taha alakhdar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Copy of as Programming Notes June 25.PDF

Uploaded by

taha alakhdar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Table of Content

1 Chapter 12: Algorithm design &Problem Solving


29 Chapter 13: Procedures, Functions,Structure Charts and FileHandling
52 Chapter 14: Data Types & Structures
64 Chapter 15: Software Development

Programming
Notes
Instagram: @megztechteam 1

Chapter 12
Algorithm design &
Problem Solving
GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 2

Algorithms A sequence of steps that can be carried out to perform a task.

Algorithm Design is the step-by-step development of instructions to solve a problem.


We can express this solution of a problem using algorithms (sequence of steps) written in:

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 any Algorithm we have


INPUT – PROCESS – OUTPUT

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.

x 3 // variable --- you should know how to write a comment.

ParkEntryCost 50 // Constant --- 2 backslashes before each new comment line

y 5 // is called Assignment operator.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 3

Atomic type names

The following keywords are used to designate atomic data types:


GZ
● INTEGER: A whole number; written as normal in the denary system, e.g. 5, -3
● REAL: A number capable of containing a fractional part (decimal); Always written with
at least one digit on either side of the decimal point, with zeros being added if
necessary, e.g. 4.7, 0.3, -4.0, 0.0.
ME

● 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).

Megz Tech Team +2 01122884770


Instagram: @megztechteam 4

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.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 5

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.

Random number generation


ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 6

Sequence
Sequence: It is the concept of one statement being executed after another.
enter = input = given = read
calculate = output = print = find = determine

Practicing Algorithms

1. Write an algorithm to input two numbers and find their sum.


2. Write an algorithm to input three numbers and find their sum.
3. Write an algorithm to input three numbers and find their average.
4. Write an algorithm to determine the flying time between two cities given the distance
between them and the average speed of the airplane.
5. Write an algorithm that calculates your BMI given your weight and height. The BMI is
calculated using the weight divided by height squared, where weight is in kg and
height is in meters.
6. Write an algorithm to enter length in centimetre and convert it into meter and
kilometre.
GZ
7. Write an algorithm to enter weight in grams and convert it into kilograms.
8. Write an algorithm to enter data in bytes and convert it in bit and gigabytes.
9. Write an algorithm that calculates the time needed to upload a file given the upload
speed and the file size.
10. Write an algorithm that calculates the time needed to upload a file in seconds given
the upload speed in Mbps and the file size in GB.
ME

11. Write an algorithm that takes as input two numbers and swaps the values of these
numbers.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 7

Selection / Conditional Statements

Selection: The process of making a decision in a program.


In a selection, a question is asked and then the correct path is taken depending on the answer
(TRUE / FALSE).

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

Example 1:

DECLARE Age : INTEGER


INPUT Age
IF Age >= 18
THEN
GZ
OUTPUT “You are an adult.”
ELSE
OUTPUT “You are not an adult.”
ENDIF
ME

Example 2:

DECLARE ExamScore : REAL


INPUT ExamScore
IF ExamScore > 50
THEN
OUTPUT “Congratulations, You’ve passed.”
ELSE
OUTPUT “Sorry, You didn’t pass.”
ENDIF

Megz Tech Team +2 01122884770


Instagram: @megztechteam 8

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

Nested IF statements: conditional statements within conditional statements


Example 5:
ME

DECLARE Number : INTEGER


INPUT Number
IF Number = 1
THEN
OUTPUT “Option 1”
ELSE
IF Number=2
THEN
OUTPUT “Option 2”
ELSE
OUTPUT “Incorrect choice”
ENDIF
ENDIF

Megz Tech Team +2 01122884770


Instagram: @megztechteam 9

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

Uses relational operators


(<, >, <=, >=, <>, (), AND, OR, NOT)
Practicing Algorithms:
1. Write an algorithm to find maximum between two numbers.
2. Write an algorithm to find maximum between three numbers.
3. Write an algorithm that determines whether you are underweight, fit, or overweight
given your weight and height based on your BMI calculation. The BMI is calculated
using the weight divided by height squared, where weight is in kg and height is in
meters.
- If BMI <= 18.5, you are underweight
- If BMI > 18.5 and BMI <= 25, you are fit
- If BMI > 25, you are overweight
4. Write an algorithm that enter in which grade the student is now prints out whether
current student is in elementary school (Grade 1 to Grade 5), middle school(Grade 6
to Grade 8), or high school (Grade 9 to Grade 12).
5. Write an algorithm to enter 3 numbers and assign the value of the largest two
numbers to a variable called Answer then print this variable.
6. Write an algorithm that inputs three numbers and outputs the product of the largest
two numbers only if the three numbers are different

Megz Tech Team +2 01122884770


Instagram: @megztechteam 10

Iteration / Repetition / Loops:


Iteration: we use iteration when some instructions need to be repeated.
Count controlled loops FOR…TO…NEXT
Pre-Condition controlled loops WHILE…DO…ENDWHILE
(The loop may never be executed)
Post-Condition controlled loops REPEAT…UNTIL
(The loop is executed at least once)

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

DECLARE Total, Count, Number : INTEGER


Total 0
Count 1
WHILE Count <= 4 DO
INPUT Number
Total Total + Number
Count Count + 1
ENDWHILE
PRINT Total

Example 3: REPEAT

DECLARE Total, Count, Number : INTEGER


Total 0
Count 1
REPEAT
INPUT Number
Total Total + Number
Count Count + 1
UNTIL Count > 4
OUTPUT Total
Megz Tech Team +2 01122884770
Instagram: @megztechteam 11

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.

Rogue Value: a value used to terminate a sequence of values.


GZ
Practicing Algorithms:
1. Write an algorithm that inputs some numbers and calculates their total of numbers,
the process ends when the user enters -1 (a rogue value = -1) using WHILE loop.
2. Write an algorithm that inputs some numbers and calculates their total of numbers,
ME

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.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 12

Nested loop: loop containing another loop.

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 13

Validation Functions:
1. Range check: (Number)

OUTPUT “Please enter the student’s mark”


REPEAT
INPUT StudentMark
IF StudentMark < 0 OR StudentMark > 100
THEN
OUTPUT “The student’s mark should be in the range 0 to 100 , please re-enter the
mark”
ENDIF
UNTIL StudentMark >=0 AND StudentMark <=100

2. Length check: (String)

OUTPUT “Please enter your password of eight characters”


REPEAT
INPUT Password
IF LENGTH(Password) <> 8
GZ
THEN
OUTPUT “Your password must be exactly eight characters, please re-enter”
ENDIF
UNTIL LENGTH(Password) = 8

3. Type check: (Number)


ME

OUTPUT “ How many brothers do you have?”


REPEAT
INPUT NumberOfBrothers
IF NumberOfBrothers <> DIV( NumberOfBrothers , 1 )
THEN
OUTPUT “ This must be a whole number, please re-enter”
ENDIF
UNTIL NumberOfBrothers= DIV ( NumberOfBrothers , 1 )

4. Presence check: (string)


OUTPUT “Please enter your email address”
REPEAT
INPUT EmailAddress
IF EmailAddress = “”
THEN
OUTPUT “you cannot leave it blank , please re-enter”
ENDIF
UNTIL EmailAddress <> “”

Megz Tech Team +2 01122884770


Instagram: @megztechteam 14

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 15

Structured English Keywords


PROMPT
INPUT (Add a user input and prompt to the enter the name of the tutor group)
PRINT – OUTPUT - DISPLAY
IF – COMPARE – CHECK
LOOP – ITERATE – REPEAT – WHILE
USE a conditional statement to – USE a loop structure to
OPEN (file) - CLOSE (file)
READ – WRITE – APPEND (File) [Open file in read mode]
DECLARE
INITIALISE
SET
GZ
ASSIGEN
INCREMENT
MODIFY
CALCULATE
ME

SEARCH
FIND

Megz Tech Team +2 01122884770


Instagram: @megztechteam 16

Programming Best Practices

Features that make the code easier to understand:

- Indentation

- Capitalization of keywords

- Comments

- White space

- Sensible / meaningful variable names OR use of Camel Case

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 17

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 18

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

StudentsMarks 🡨 [40, 39, 80, 36, 29] // StudentsMarks[1:5]


Reading from an Array:

PRINT StudentsMarks[1] // The program will print ………………..


PRINT StudentsMarks[4] // The program will print ………………..
Count 🡨 2
PRINT StudentsMarks[Count] // The program will print ………………..

Writing to an Array:

StudentsMarks[3]🡨25 //The array will be updated to……...…………………………………………


StudentsMarks[1]🡨50 // The array will be updated to ……………………………………………….
Count 🡨 4
StudentsMarks[Count]🡨33 // The array will be updated to ………………………………………

Arrays are considered to be fixed-length structures of elements of identical data type,


accessible by consecutive index (subscript) numbers. It is good practice to explicitly state what
the lower bound of the array (i.e. the index of the first element) is because this defaults to
either 0 or 1 in different systems. Generally, a lower bound of 1 will be used.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 19

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

array called ListA.


6. Write an algorithm that outputs the smallest number of 100 numbers stored in an
array called ListA.
7. Write an algorithm that outputs how many numbers are greater than 20 in an array
called ListA (Assume that the array stores 100 numbers).
8. Write an algorithm that outputs the total of numbers that are greater than 20 in an
array called ListA (Assume that the array stores 100 numbers).
9. Write an algorithm that prints out the average of numbers that are greater than 20
in an array called ListA.
10. Write an algorithm that prints out how many numbers are negative in an array called
ListA (Assume that the array stores 100 numbers).
11. Write an algorithm that prints out the product of the positive numbers only in an
array called ListA (Assume that the array stores 100 numbers).
12. Write an algorithm that outputs 100 numbers in an array called ListA.
13. Write an algorithm that inputs 100 numbers inside an array called ListA and outputs the total
of numbers greater than 20 inside the array. Validate each number to be between 0 & 300
(FOR Loop)

14. Write an algorithm that inputs 100 numbers inside an array called ListA and outputs the
product of the positive numbers only (WHILE Loop)

Megz Tech Team +2 01122884770


Instagram: @megztechteam 20

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

Megz Tech Team +2 01122884770


Instagram: @megztechteam 21

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.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 22

Bubble Sort: a sort method where adjacent pairs of values are compared & swapped.

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 23

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 24

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 25

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 26

GZ
ME

Practicing Algorithms:
1. Write an algorithm that sorts an array called ListA ascendingly. ListA stores 100
numbers.

2D arrays

Megz Tech Team +2 01122884770


Instagram: @megztechteam 27

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 28

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

Megz Tech Team +2 01122884770


Instagram: @megztechteam 29

Chapter 13
Procedures, Functions,
Structure Charts and File
Handling
GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 30

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.

N.B. Procedures and Functions can be with or without parameters

Megz Tech Team +2 01122884770


Instagram: @megztechteam 31

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.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 32

Stepwise refinement

Modules

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 33

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 34

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.

→ String manipulation functions:

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 35

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

Returns same string with all letters in lowercase

SUBSTRING
SUBSTRING ( “Computer” , 2 , 3 ) → omp
⬇ ⬇ ⬇
String Starting Number of characters
Index
SUBSTRING ( “ Computer Science” , 1 , 4 ) → Comp
--------------------------------------------------------------------------------

Megz Tech Team +2 01122884770


Instagram: @megztechteam 36

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(6.8694 , 2) ROUND(7.88 ,1)


⬇ ⬇ 7.9
GZ
REAL Number of
decimal places
6.87

ROUND(5.694 , 0)
ME

INT(5.694)
5

RANDOM
X ← RANDOM ( )
Returns a random number between 0 & 1 inclusive

Megz Tech Team +2 01122884770


Instagram: @megztechteam 37

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 38

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 39

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.

Passing parameters to procedures


If a parameter is passed by value, at call time the argument can be an actual value (as we
showed in the previous example). If the argument is a variable, then a copy of the current value
ME

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.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 40

Passing parameters by value

Passing parameters by reference

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.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 41

How to draw the procedure/function box in flowchart ??

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

the returned value to a variable called y.


9. Write a Function called GreaterTwenty that takes in 3 numbers and
returns the count of numbers greater than 20.
10.Write a programming statement to call the Greater20 function and assign
the returned value to a variable called z.
11.Write a function that takes 2 strings as a parameter and returns whether
the 2 strings are equal in size or not.
12.Write a procedure that takes 2 strings as a parameter and prints whether
the 2 strings contain the same number of letter ‘a’.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 42

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

Megz Tech Team +2 01122884770


Instagram: @megztechteam 43

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 44

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 45

What is the purpose of a Structure chart?


● Shows how a problem is broken down.
● shows the relationships between the modules.
● Shows the parameters that are passed down between modules.
● Shows whether the module is a function or a procedure

Structure Chart

● a graphical representation of the modular structure of a solution.


● Each box of the structure chart represents a module.
● Each level is a refinement of the level above.
● Parameter is a value passed between modules.
● 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 diamond shape shows a condition that is either True or False.
● Semi-circular arrow represents repetition of the modules below the arrow.

Turning Structure Chart into Pseudocode


● Top-Level Block is a MODULE.
GZ
● Every Block Beneath it is either a FUNCTION (if it has an arrow pointing up) or a
PROCEDURE (if there is no arrow pointing up from it)
● If a single parameter is passed both ways (arrow up and down) then pass it by
reference
● For the diamond shape use IF
● For the circular arrow use a Loop Structure
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 46

MODULE NumberGuessingGame
SecretNumber = GenerateSecretNumber()
GZ
Guess = InputGuess()
CALL OutputMessage(Guess, SecretNumber)
ENDMODULE

FUNCTION GenerateSecretNumber() RETURNS INTEGER


RETURN RANDOMBETWEEN(1,100)
ME

ENDFUNCTION

FUNCTION InputGuess() RETURNS INTEGER


DECLARE Num : INTEGER
INPUT Num
RETURN Num
ENDFUNCTION

PROCEDURE OutputMessage(BYVAL Guess : INTEGER, BYVAL


SecretNumer : INTEGER)
IF Guess = SecretNumber THEN
OUTPUT “Congratulation”
ELSE
OUTPUT “Sorry! Better luck next time!”
ENDIF
ENDPROCEDURE

Megz Tech Team +2 01122884770


Instagram: @megztechteam 47

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

FUNCTION GetNumber() RETURNS INTEGER


DECLARE Number : INTEGER
INPUT Number
RETURN Number
ENDFUNCTION

FUNCTION isLarger(BYREF Max:INTEGER, BYVAL Number:INTEGER) RETURNS BOOLEAN


IF Max < Number THEN
Max = Number
RETURN TRUE
ENDIF
RETURN FALSE
ENDFUNCTION

PROCEDURE OutputChange()
OUTPUT “This Value is currently the largest“
ENDPROCEDURE

PROCEDURE OutputMax(Max : INTEGER)


OUTPUT Max
ENDPROCEDURE

Megz Tech Team +2 01122884770


Instagram: @megztechteam 48

File Handling

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 49

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

File Handling operations includes:


-create
-open
-read
-write
-close

Megz Tech Team +2 01122884770


Instagram: @megztechteam 50

Handling random files

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 51

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

Megz Tech Team +2 01122884770


Instagram: @megztechteam 52

GZ
ME

Chapter 14
Data Types & Structures

Megz Tech Team +2 01122884770


Instagram: @megztechteam 53

Chapter 14: Data Types & Structures

1. Built-in Data Types:


INTEGER A signed whole number
Example: 25, -4, …etc.
REAL A signed number with a decimal point
Example: -2.3, 4.8, …etc.
CHAR A single alphanumeric character
Example: ‘A’, ‘@’, …etc.
STRING A sequence of characters
Example: “Computer”, “12”, …etc.
BOOLEAN The logical values TRUE (represented as 1) and FALSE (represented as 0)
DATE A date consisting of day, month and year, sometimes including a time in
hours, minutes and seconds

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

Megz Tech Team +2 01122884770


Instagram: @megztechteam 54

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

2. Variable Declaration of Record Type:


DECLARE <variable identifier> : <record type>
GZ
Example:
DECLARE Person: Student
3. Assigning Values to Fields of The Record:
<variable identifier> . <field name> : value
Example:
Person.Name “Ahmad”
ME

Person.ID “123456789”
Person.Age  16
Person.DateOfBirth  4/4/2004

Megz Tech Team +2 01122884770


Instagram: @megztechteam 55

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

Megz Tech Team +2 01122884770


Instagram: @megztechteam 56

4. Abstract Data Types (ADT):


Abstract Data Type: a collection of data with associated operations. Some of the
operations are:
● create a new instance of the data structure
● find an element in the data structure
● insert a new element into the data structure
● delete an element from the data structure
● access all elements stored in the data structure in a systematic manner

For each abstract data type, we will implement it using 1D array.


4.1. Stacks:
A stack is an abstract data structure that is represented as an array of
data/elements that have the same data type. It follows “Last in First out”
(LIFO). That is, the last element that was inserted (pushed) is the first element
to be removed (popped).
GZ
ME

● BaseOfStackPointer always points to the first slot in the stack.


● TopOfStackPointer points to the last element that has been pushed into the
stack.
● When an element is removed/popped, the TopOfStackPointer decreases to
point to the current top element of the stack.
● TopOfStackPointer has value -1 when the stack is empty.
Stack Declaration:
DECLARE Stack: ARRAY [<lowerBound>:<upperBound>] OF <dataType>
Example:
DECLARE Stack: ARRAY [0:7] OF CHAR
4.2. Queues:
A queue is an abstract data structure that is represented as an array of
data/elements that have the same data type. It follows “First in First out”
(FIFO). That is, the first element that was inserted (enqueued) is the first
element to be removed (dequeued).
1. Linear Queue:
● FrontOfQueuePointer points to the first slot in the queue (array index = 0),
which has the first element to be dequeued/removed.
● EndOfQueuePointer points to the last element inserted/enqueued. This will
be the last element to be dequeued/removed.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 57

● 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.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 58

4.3. Linked Lists:

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.2. Inserting a new node at the end of a linked list:

Megz Tech Team +2 01122884770


Instagram: @megztechteam 59

1.3. Inserting a new node within two existing nodes in a linked list:

2.1.Deleting the first node in a linked list:

2.2.Deleting the last node in a linked list:


2.3.Deleting a node within a linked list:
GZ
Advantage: Linked lists are more efficient than linear lists (arrays). When
deleting/inserting, only pointers need changing instead of moving all
elements/data.
Disadvantage: Need more storage space for the pointer fields.
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 60

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.2. Inserting a new node at the end of a linked list:

Megz Tech Team +2 01122884770


Instagram: @megztechteam 61

1.3. Inserting a new node within two existing nodes in a linked list:

2.1.Deleting the first node in a linked list:


2.2.Deleting the last node in a linked list:

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 62

2.3.Deleting a node within a linked list:

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.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 63

1. Adding data to the linked list:

2. Deleting data from the linked list:


Deleting ‘D’ from the linked list.

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 64

Chapter 15
Software Development
GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 65

Why have a software development life cycle?


● Easier to manage and plan software system.
● Clear Deliverables produced at the end of each stage.
● e.g. When large software systems are required to solve big problems, or when more
people are involved in the department

What are Stages in the program development life cycle?


● Analysis
● Design
● Coding
● Testing
● Maintenance

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

● An Identifier Table is Produced.


● Decide on your data structures.
Coding (Implementation)
● Choose a suitable high-level programming language.
● You implement your algorithm by converting your pseudocode into program code.
Testing
● Does the program do what it was meant to do?
● Ensure the program really works under all circumstances

When the program works and is being used, issues might arise that require changes. This is
known as Maintenance.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 66

The Program development life cycle

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.

What are the Iterative Model’s principals?

1. Development starts with the implementation of a small subset of the program


requirements.
2. Repeated (iterative) reviews to identify further requirements eventually result in the
complete system.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 67

What are the Rapid Application Development (RAD) model’s principals?

● Uses minimal planning.


● Instead it uses prototyping.
● A prototype is a working model of part of the solution.
● The modules are developed in parallel as prototypes and are integrated to make the
complete product for faster product delivery.

Model Benefits Drawbacks


Waterfall ● Simple to understand as the stages are clearly ● No working software is
defined. produced until late during the
● Easy to manage due to the fixed stages in the life cycle.
model. Each stage has specific outcomes. ● Not a good model for complex
● Stages are processed and completed one at a and object-oriented projects.
time. ● Poor model for long and
● Works well for smaller projects where ongoing projects.
requirements are very well understood. ● Cannot accommodate changing
requirements.
● It is difficult to measure
progress within stages.
GZ ● Integration is done at the very
end, which doesn’t allow
identifying potential technical
or business issues early.

Iterative There is a working model of the system at a ● Only large software


ME


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.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 68

● Better suited for large and mission-critical


projects.
● During the life cycle, software is produced
early, which facilitates customer evaluation and
feedback.

RAD ● Changing requirements can be accommodated. ● Only systems that can be


● Progress can be measured. modularised can be built using
● Productivity increases with fewer people in a RAD.
short time. ● Requires highly skilled
● Reduces development time. developers/designers.
● Increases reusability of components. ● Suitable for systems that are
● Quick initial reviews occur. component based and scalable.
● Encourages customer feedback. ● Requires user involvement
● Integration from very beginning solves a lot of throughout the life cycle.
integration issues. ● Suitable for projects requiring
shorter development times.
GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 69

State Transition Diagram (Finite State Machine)


● A computer system can be seen as a finite state machine (FSM).
● a machine that consists of a fixed set of possible states with a set of inputs that
change the state and a set of possible outputs
● An FSM has a start state. (denoted by an arrow with a solid round end)
● An input to the FSM produces a transformation from one state to another state.
● The information about the states of an FSM can be presented in a state-transition

table.

● A State-Transition Diagram: a diagram that describes the behavior of an FSM


● If an Input (at a given state) causes an output this is shown by the vertical bar.

GZ
ME

N.B. State transition diagram can with or without an output

Megz Tech Team +2 01122884770


Instagram: @megztechteam 70

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 71

GZ
ME

Why is it that Software may not perform as expected?


● the programmer has made a coding mistake
● the requirement specification was not drawn up correctly
● the software designer has made a design error
● the user interface is poorly designed, and the user makes mistakes
● computer hardware experiences failure.

What are the Different Types of Errors and their descriptions?


● Syntax error: an error in which a program statement does not obey the rules and
grammar of the language
● Logic error: an error in the logic of the solution that causes it to not behave as
intended
● Run-time error: an error that causes program execution to crash or freeze such as
performing an illegal operation like dividing by zero.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 72

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.

Megz Tech Team +2 01122884770


Instagram: @megztechteam 73

How to Dry-run or Trace an algorithm?

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).

Megz Tech Team +2 01122884770


Instagram: @megztechteam 74

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 75

How to choose Test Data for a problem?


● Pick Normal Data: values that are expected and would cause normal program
operation
● Pick Abnormal Data: values that are not expected and should cause an error prompt to
the user
● Pick Extreme Data: Accepted Data just at the edges e.g. 0 and 100 for exam scores.
● Pick Boundary Data: extreme data and boundary data e.g. -1, 0, 100, 101 for exam
scores.

How to prevent errors?


● tried and tested design techniques such as structured programming or object-oriented
design
● conventions such as identifier tables, data structures and standard algorithms
● tried and tested modules or objects from program libraries.

What are the different types of maintenance?


● Corrective Maintenance: correcting identified errors, as the program does not
operate as expected.
● Adaptive Maintenance: amending program to enhance functionality in response to
specification or technology changes. e.g. New HTML version is available
● Perfective Maintenance: modifying program to improve performance or
maintainability.
GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 76

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 77

GZ
ME

Megz Tech Team +2 01122884770


Instagram: @megztechteam 78

GZ
ME

Megz Tech Team +2 01122884770

You might also like