0% found this document useful (0 votes)
13 views

P2 Unit 8 - Programming Concepts

Uploaded by

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

P2 Unit 8 - Programming Concepts

Uploaded by

vijahat
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Data Structure

Arrays ( 1D and 2D) , linear search, max, min, bubble sort


Declare an Array
names
• An array is a data structure 1
that allows you to hold many 2
items of data which is 3
referenced by one identifier ( dimension) 4
5
• All items of data in the array must
6
be of the same data type
7
Declare an array of 10 string/ text called 8
Names could be 9
declared as: 10
• DECLARE names : ARRAY[1:10] OF STRING
Data types
• For the variables given, the data types would be:
• numberOfStudents Integer
• circleArea Real
• found Boolean
• answer Char
• studentName String
• DateOfBirth Date
Arrays
names
• Information can be read 1 "psmith"
from or added to the array using 2 "ltorvalds"
the index number (in pseudocode 1) 3 "pwatts"
4 "sjones"
• To add five usernames we would use:
5 "mpatel"
DECLARE Username : ARRAY[1:10] OF STRING
6 ……….
names[1] ← "psmith"
names[2] ← "ltorvalds" 7 ……….
names[3] ← "pwatts" 8 …………
names[4] ← "sjones" 9 ………….
names[5] ← "mpatel“
10 …………
………………………………………..
output LENGTH(names) #this returns 10
How to output Arrays items
names
FOR i ← 1 TO LENGTH(names) 1 "psmith"
OUTPUT names[i] 2 "ltorvalds"
NEXT i
3 "pwatts"
4 "sjones"
5 "mpatel"
6 "bwright"
7 "mgreen"
8 "dthomas"
9 "nwhite"
10 "fdavies"
Total and Average - Arrays
Declare Price : Array [1:5] of Real
Declare Total : Real
Total = 0.0
Price = [ 0.99, 1.28,3.69, 0.49. 8.29]
For i 1 to LENGTH ( Price)
Total = Total + Price[i]
Next i
print “ Average price is” , Total/ 5
Using two arrays
• Two arrays could be used to store different items
• For example, the price and quantity of products ordered on
a website. Assume arrays are already declared and price and quantity is
already assigned to the arrays
Price Quantity
1 0.99 1 2
2 1.28 2 3
3 3.69 3 1
4 0.49 4 4
5 8.29 5 1
Using two arrays
• Write a program in pseudocode to work out the total
price of the order
DECLARE TotalPrice : REAL
Declare ItemsPrice : REAl
TotalPrice= 0
FOR i ← 1 TO LENGTH(Price)

ItemsPrice  Price[i] * Quantity[i]


TotalPrice  TotalPrice + ItemsPrice
NEXT i
OUTPUT "Total price: ", TotalPrice
Linear search an array ( item not found)
OUTPUT "Type in a name to search: "
INPUT Search
Found = False
Search= LCASE( Search)
names
FOR i ← 1 TO LENGTH(names) 1 "smith"
IF names[i] = Search
THEN 2 "torvalds"

output ‘Name is found’ 3 "watts"


Found = True 4 "jones"
ENDIF
NEXT i 5 "patel"
6 "wright"
If Found == False then
7 "green"
output ‘Name is not found’
8 "thomas"
End if
9 "white"
10 "davies"
Standard Max Algorithm
Rain = [ 1.1, 0. 51, 3.1, 0.1, 3.2]
Max
Max = Rain [ 1] 1.1
0.51
For index 1 to 5
3.1
if Rain[ Index] > Max 0.1
3.2
Max = Rain[ index]
End If
Next index
Output(' the max rainfall is ‘, Max)
Why do we set ‘highest’ to 0 and ‘lowest’ to 100000?
Consider this code, which inputs the average daily In the first iteration of the FOR loop, the first value
inches of rainfall in England for 6 months, and sets will (likely) satisfy both conditions and therefore
the variable ‘lowest’ to the value of the lowest the code will set both variables ‘highest’ and
rainfall entered, and sets the variable ‘highest’ to ‘lowest’, to the value of the first measurement
the value of the highest rainfall entered: entered, since the value could be the highest or
the lowest.
highest  0
lowest  100000 Consider the following test data of average daily
inches of rain:
0.3, 1.1, 3.1, 3.7, 4.2, 3.2.
FOR count  1 TO w6
INPUT averageInches As the variable ‘highest’ was assigned 0 at the
IF averageInches > highest THEN start, the first value above 0 will be set as
highest  averageInches ‘highest’; subsequent higher values will update
ENDIF the value of the variable ‘highest’. If we initialized
IF averageInches < lowest THEN ‘lowest’ to 0 as well, the first measurement of 0.3
lowest  averageInches (the lowest in the list), will not set ‘lowest’ to 0.3.
ENDIF
NEXT This is why we initialize the ‘lowest’ variable to a
high number at the start of a pseudocode
algorithm. Of course, for this example, 100000 is
OUTPUT highest, lowestt
excessive, but you should set it to a value you
know is more than a possible ‘lowest’ input.
Two-dimensional arrays
• Suppose you wanted to hold in a program, five
marks for each of three students Columns

Row

• These marks could be put into a 2D array with 3


rows and 5 columns
Declare 2D array and assign
values Columns

Row

Declare Marks : Array [ 1:3, 1: 5] of integer


Output of a 2D array
Columns
Row

For Row 1 to 3
For Col 1 to 4
print Marks [Row][Col]
Next Col
Next Row

* A for loop inside a for loop, is a nested for loop


Total of all the values in a 2D array
Columns

Row

Total =0
For Row 1 to 3
For Col 1 to 5
Total = Total + Marks [Row] [ Col ]
Next Col
Next Row
Print ‘ Total of all the values is’ , Total
Total of the values in each row in a 2D array

Total= 0
For Row 1 to 3
RTotal =0
For Col 1 to 5
RTotal = RTotal + Marks [Row] [ Col ]
Next Col
Output ‘ Row total is’, Rtotal
Total = Total + RTotal
Next Row
Print ‘ Total of all the values is’ , Total
The bubble sort
• Start with the leftmost item
• Compare this item with the one next to it
• If the one next to it is less, swap the items
• Repeat for all the other items
• At the end of one pass through the list, the largest item is at
the end of the list
• Repeat the process until the items are sorted
• Suppose you have a list of numbers to be sorted:

9 5 4 15 3 8 11 2
Bubble sort – First pass
9 5 4 15 3 8 11 2 • Each item is compared
5 9 4 15 3 8 11 2 with the one on its right,
and swapped if it is
5 4 9 15 3 8 11 2
larger
5 4 9 15 3 8 11 2
• At the end of the first
5 4 9 3 15 8 11 2 pass the largest item
5 4 9 3 8 15 11 2 bubbles through to the
end of the list
5 4 9 3 8 11 15 2
• (Orange indicates
5 4 9 3 8 11 2 15
sorted items)
First pass Second pass
9 5 4 15 3 8 11 2 5 4 9 3 8 11 2 15

5 9 4 15 3 8 11 2 4 5 9 3 8 11 2 15

5 4 9 15 3 8 11 2 4 5 9 3 8 11 2 15

5 4 9 15 3 8 11 2 4 5 3 9 8 11 2 15

5 4 9 3 15 8 11 2 4 5 3 8 9 11 2 15

5 4 9 3 8 15 11 2 4 5 3 8 9 11 2 15

5 4 9 3 8 11 15 2 4 5 3 8 9 2 11 15

5 4 9 3 8 11 2 15
Second pass Third pass
5 4 9 3 8 11 2 15 4 5 3 8 9 2 11 15

4 5 9 3 8 11 2 15 4 5 3 8 9 2 11 15

4 5 9 3 8 11 2 15 4 3 5 8 9 2 11 15

4 5 3 9 8 11 2 15 4 3 5 8 9 2 11 15

4 5 3 8 9 11 2 15 4 3 5 8 9 2 11 15

4 5 3 8 9 11 2 15 4 3 5 8 2 9 11 15

4 5 3 8 9 2 11 15
Third pass Fourth pass
4 5 3 8 9 2 11 15 3 4 5 8 2 9 11 15

4 5 3 8 9 2 11 15 3 4 5 8 2 9 11 15

4 3 5 8 9 2 11 15 3 4 5 8 2 9 11 15

4 3 5 8 9 2 11 15 3 4 5 8 2 9 11 15

4 3 5 8 9 2 11 15 3 4 5 2 8 9 11 15

4 3 5 8 2 9 11 15
Fourth pass Fifth pass
3 4 5 8 2 9 11 15 3 4 5 2 8 9 11 15

3 4 5 8 2 9 11 15 3 4 5 2 8 9 11 15

3 4 5 8 2 9 11 15 3 4 5 2 8 9 11 15

3 4 5 8 2 9 11 15 3 4 2 5 8 9 11 15

3 4 5 2 8 9 11 15
Fifth pass Sixth pass
3 4 5 2 8 9 11 15 3 4 2 5 8 9 11 15

3 4 5 2 8 9 11 15 3 4 2 5 8 9 11 15

3 4 5 2 8 9 11 15 3 2 4 5 8 9 11 15

3 4 2 5 8 9 11 15

Sixth pass Seventh pass


3 4 2 5 8 9 11 15 3 2 4 5 8 9 11 15

3 4 2 5 8 9 11 15 2 3 4 5 8 9 11 15

3 2 4 5 8 9 11 15 Seven passes through the list of eight


numbers ensures that they are sorted
Swapped = True
N= Array. Length
While ( Swapped)
Swapped = false
for index 1 to N -1
if ( num[index] > num[index+1]
temp= num[index]
num[index]= num[index+1]
Bubble Sort num[index+1]= temp
Swapped= True
algorithm endif
Next index
N= N-1
End while
Library Routines
Why use Library routines
Library routines are algorithms which programmers
have made and are ready to use by other
programmers without developing them from scratch
• They can be reused by other programmers
• You don’t need to know how the algorithms work in order
to use them – Values are passed to the routine, processing
is done and required value is returned
• Efficient programming, routines are called when they are
required. Programmers doesn’t have to program from scratch,
they can reuse them
Rounding numbers
• The ROUND function will round a number to the
number of decimal places given as <places>
ROUND(<identifier>, <places>)
• ROUND(5.287, 2) returns 5.29
• Round 18.7356 to one decimal place
ROUND(18.7356, 1)
• Round a variable Distance (in metres) to the nearest cm
ROUND(Distance, 2)
• Round the variable Age to the nearest whole year
ROUND(Age, 0)
Random numbers
• A random number between 0 and 1 is generated with the
following pseudocode:
RANDOM()
• This returns a number such as 0.13984
Please note that Random ( ) returns decimal number.

• A random number between 0 and 100 can then be generated


with a statement such as
RANDOM() * 100 # returns decimal number between 0 to 100
To make it an integer between 0, 100 but not decimal
ROUND(RANDOM() * 100, 0)
Random number between 0, 50
ROUND(RANDOM() * 50, 0)
Random numbers
How could you simulate the throw of a dice?
• Pseudocode:

Dice ← ROUND(RANDOM()*6,0)
OUTPUT Dice
• Python:
import random
dice = random.randint(0, 6)
print(dice)
MOD and DIV
• Some languages will use MOD and DIV as library
routines.
• For instance
MOD(5,2) returns 1 // Divides 5 by 2 and return remainder
DIV(7,3) returns 2 // Divides 7 by 3 and return
quotient
DIV ( 3, 10 ) returns 0 // Divides 3 by 10 and returns quotient
MOD ( 3,10 ) returns 3 // Divides 3 by 10 and returns remainder
• In IGCSE pseudocode the MOD and DIV are operators:
5 MOD 2 evaluates to 1
7 DIV 3 evaluates to 2
Functions and Procedures
Subroutines :Functions and procedures
In contrast to library routines functions and procedures are
subroutines which programmers can code. Subroutines
allow code that you intend to use a number of times to
be grouped together under one name
• Both functions and procedures are subroutines
• Values can be passed to both procedures and functions -
parameters
• Functions returns a value after processing has taken place
• Functions and procedures are activated ( starts execution when
they are called)
• Procedure doesn’t return a value
PROCEDURE Doesn’t Return A Value
PROCEDURE greatest(a: Integer, b: Integer, c: Integer)
IF a > b AND a > c Three parameters are declared in
THEN this procedure heading
output a
IF b > a AND b > c
THEN
output b
ELSE
Output c
END PROCEDURE
Procedure is called by using the
CALL greatest( 45, 35, 40) keyword Call
Functions
Functions work just like procedures, except they return a value
FUNCTION sum(a: Integer, b:Integer) return Integer
Declare total: Integer
total ← a + b
RETURN total This is a function as it
returns a value
ENDFUNCTION

Function call, note function is not


answer ← sum(5, 3) called with the keyword, as
OUTPUT answer function returns a value so it
must be assigned to a variable
Functions
FUNCTION sum(a: Integer, b:Integer) return Integer
Declare total: Integer
total ← a + b • First sum(5,3) calls the sum function
• The values 5 and 3 are passed to
RETURN total the sum function
ENDFUNCTION • The sum function adds 5 + 3 and
stores 8 in total
answer ← sum(5, 3) • The sum function returns the result
OUTPUT answer of 8 to the function call
• This is then assigned to the variable
called answer
Output: 8 • answer (which contains 8) is then
output
FUNCTION sum(a: Integer, b:Integer) return Integer​

Declare total :Integer


total ← a + b​

RETURN total​

ENDFUNCTION​

answer ← sum(5, 3)​


OUTPUT answer
Features of Subroutines
Why use subroutines( Functions/ procedures) ?
• They are useful to break up a large program into
self-contained units
• Each subroutine can be tested separately to make sure it
works correctly
• Many programmers can work on a large program at the same
time, cutting down development time
• Subroutines can be re-used in other programs
• Subroutines can be stored in a subroutine library and used in
different programs if required
• Program maintenance is easier – if requirements change then
just the affected subroutines need to be modified
Local and global variables
• Local variables only exist while the function or
procedure is executing. They are inside the body of
a function / procedure
• They are only accessible within the particular function
or procedure
• Global variables are accessible anywhere in
the program , outside and even inside the functions
and procedures
What is output by this program?
PROCEDURE changeNum
Declare num: Integer This num variable is a local
variable
num ← 6
This procedure Outputs 6
OUTPUT num
ENDPROCEDURE
#Main program
num ← 5
OUTPUT num Outputs 5, This num variable
is global variable
#call function changenum
Calls changeNum
CALL changeNum
Outputs 5
OUTPUT num
Function example with a Constant
Function areaCircle( R: REAL ) Return REAL
Constant Pi : REAL
Pi= 3.14 # Pi is constant, never changes
Area = Pi* ( R *R)
Return Area
ENDFunction

Output ' Input the radius of the circle'


Input radius
Output ' Area is ', areaCircle ( radius)
Flow chart symbol for subroutine

Decision –
Input / Output change flow
based on a
Process – Maths decision
operations and
assignment of variables
Sub program –
Line – shows call a different
direction of flow function or
procedure
Terminal – for
start and stop
Sub programs
• Sub programs are used when you wish to call
another procedure or function
• They use a box
with lines either side Start
findVAT(n)
• In this example,
findVAT is called INPUT total VAT  n * 0.2
from the
sub program box total  total + Return VAT
• The findVAT sub findVAT(total)
program then runs
OUTPUT
and returns the total
answer to where
it was called Stop
total = total + count
File Handling
Why use files , why not
variables and arrays
• Variables and arrays are deleted after program execution is complete, data in
files is permanent and it remain in the files after the program execution is
completed
• data can be used by more than one program or reused when a program is run
again
• data can be backed up or archived
• data can be transported from one place / system to another.
Three steps of Reading and writing to files
• Reading from and writing to files requires the
following steps:
• Open the file
• Read from, or write to, the file
• Close the file

• If the file doesn’t yet exist it


will need to be created first to read
• If the file doesn’t exist it will be created if it is open to
write
Reading from a text file
• Reading from a text file involves
opening the file, processing each line
then closing the file
Declare line: String Open “marks.txt”

OPEN marks.txt FOR READ Loop through each line in the file

WHILE NOT EndOfFile DO Read the next line

READFILE marks.txt, line Output the line

OUTPUT line
ENDWHILE Close “marks.txt”

CLOSEFILE marks.txt
Creating/ open a file to write
• To create a new file use the code:
OPENFILE FileA.txt FOR WRITE
• A file needs to be opened
before it can be written to
• FileA.txt can now be written
to in the rest of the program
• When creating the file (in
IGCSE pseudocode) opening
the file in WRITE mode will
create a new file, losing any
original data if the file
already existed
Writing data to a text file
• Here is an algorithm which writes to a text file:
OPENFILE marks.txt FOR WRITE
INPUT name
INPUT mark
record  name + "," + mark + "\n"
WRITEFILE marks.txt, record
CLOSEFILE marks.txt
• If the user’s name is “Sandra” and their mark is 85
the following will be added to the file:
Sandra, 85
• \n means create a new line in the file
Closing a file
• Once you have finished reading or writing to a file it
is important to close it
• This frees up any memory used by having it open
• Once closed, the file cannot be read from or written to without
opening it again
• To close a file, use:
CLOSEFILE filename
How to make program
maintainable and readable
Maintainable programs
• Programs are easy to maintain (read, understand
and make changes to) when
• They use meaningful identifiers for variables, constants,
arrays, procedures and functions
• They have useful comments that are relevant and appropriate
to each block of code
• They make use of procedures and functions to make program
modular
• Good use of indentation and whitespace, makes program
more readable

You might also like