[go: up one dir, main page]

0% found this document useful (0 votes)
67 views150 pages

AS Pseudocode Notes Paper2

notes

Uploaded by

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

AS Pseudocode Notes Paper2

notes

Uploaded by

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

Programming Notes

for 9618
Paper - P2

Computer Science
Paper-2
9618

Shyam Subrahmanya
P2 Computer Science 9618

Contents
What is an Algorithm? ..................................................................................................................... 5
What is the difference between a Pseudocode and a program flowchart? .............................................. 5
Precedence ........................................................................................................................................... 14
Control Structures ................................................................................................................................. 18
Formats of Control Structures ............................................................................................................ 18
Sequence ............................................................................................................................................... 18
Selection ............................................................................................................................................... 19
 If _Then_ EndIf ......................................................................................................................... 19
 Case Structure............................................................................................................................ 19
ITERATION ............................................................................................................................................. 31
Comparison between While, Repeat and For loop (Pseudocode) ........................................................... 36
Practice questions ................................................................................................................................. 39
Rogue value ................................................................................................................................... 40
'Menu driven program........................................................................................................................... 44
When to use ← and =........................................................................ 47
String operations ................................................................................................................................... 50
Random Number Generator .................................................................................................................. 68
Subroutines ........................................................................................................................................... 69
User Defined functions / Built-in functions ............................................................................................ 70
Differences ........................................................................................................................................ 70
Similarities ........................................................................................................................................ 70
Procedure Vs Function........................................................................................................................... 71
Passing parameters to subroutines .......................................................................................................... 76
Arguments/ Parameters .......................................................................................................................... 76
Different ways of Calling a Function ....................................................................................................... 81
Parameter passing by value/ by reference ......................................................................................... 84
Global Variables Vs Local Variables ................................................................................................ 90
Private Scope Vs Public Scope ........................................................................................................ 90
Arrays.................................................................................................................................................... 91
Arrays ................................................................................................................................................... 92

Teacher : Shyam Subrahmanya 1|P a ge


P2 Computer Science 9618

1D Vs 2D Array .................................................................................................................................. 98
Single Search Result......................................................................................................................... 104
Multiple Search Result ..................................................................................................................... 104
Case insensitive search .................................................................................................................... 104
Case sensitive search ....................................................................................................................... 104
2D Array .............................................................................................................................................. 119
File Operations .................................................................................................................................... 124
File handling ........................................................................................................................................ 125
Example1- Write data on file ........................................................................................................... 126
Example 2a- Append data ................................................................................................................ 128
Example 2b-Append Data in a loop .................................................................................................. 128
Example 3 – Read data from file ...................................................................................................... 129
Using 2 files ..................................................................................................................................... 130
Rouge Value & File handling ............................................................................................................ 131
2 different file structures ................................................................................................................. 136
Searching in a Text File Vs Searching in an Array .............................................................................. 142
SUMMARY OF FORMATS ..................................................................................................................... 143

Teacher : Shyam Subrahmanya 2|P a ge


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 3|P a ge


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 4|P a ge


P2 Computer Science 9618

Programming Basics
What is an Algorithm?
An algorithm is a series of instructions or steps for the solution of a problem.

What is the difference between a Pseudocode and a program flowchart?


An algorithm can be represented by a Pseudocode (Set of statements) or
a program flowchart (using symbols)

Pseudocodes
(English statements)
Algorithm Converts to
(Program design)
Program flowchart
(graphical representation
of a solution)

Program code on
computer

Teacher : Shyam Subrahmanya 5|P a ge


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 6|P a ge


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 7|P a ge


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 8|P a ge


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 9|P a ge


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 10 | P a g e


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 11 | P a g e


P2 Computer Science 9618

Data types
Pseudocode

STRING

DATE

CHAR

BOOLEAN

INTEGER

CURRENCY

REAL

 Note

Variable average is always Real data type because it involves a divide operation.

Teacher : Shyam Subrahmanya 12 | P a g e


P2 Computer Science 9618

Pseudocode FORMATS

DECLARE <identifier> : <data type>

DECLARE Count : integer

CONSTANT <identifier> = <value>

CONSTANT Pi=3.14

CONSTANT Tax=10

<identifier> ← <value> or <expression>

Count ← 0

Count ← Count+1

INPUT <identifier>

INPUT Marks

OUTPUT <string>

OUTPUT “Hello”

OUTPUT <identifier(s)>

OUTPUT Marks

// this is a comment

Teacher : Shyam Subrahmanya 13 | P a g e


P2 Computer Science 9618

Built-in functions

Result ← 2^3 //^ represents exponent, result is 8

Num ← INT (3.5)

//INT is a built in function, returns only integer part of the decimal number, Num is 3

Num ← 5/2 //Normal division, answer is 2.5

Precedence

B Brackets

E Exponent

D Divide and Multiply has the same level of precedence. Priority is


given to the operator on the left.
M

A Add and subtract has the same level of precedence. Priority is given
to the operator on the left.
S

Solve Number = 2* 6 + 8 / 2 ^ 2

Teacher : Shyam Subrahmanya 14 | P a g e


P2 Computer Science 9618

Ans is 14

Declaration To reserve memory space according to array size and data type. Once the
memory is reserved there are junk values from previous programs in the memory.

Initialization To assign a valid starting value to an identifier. Now the junk value will be
replace by the initialization value. It is optional to initialize the variables that are being input.
It is mandatory to initialize variables that are being processed example count, total, max, min.

Statements (Pseudocodes)
Assignment
x ← 3 means the value 3 is written as the new value stored in the memory location labelled x,
x ← y means the value stored in the memory location labelled y is copied to the memory location
labelled x

Increment (Counting)
Variable ← Variable + 1

Example

count ← count+1

Statement used to increment variable by 2 (step size is 2)

Variable ← Variable + 2

Example

count ← count+2 (can be used for even or odd number list)

Statement used to increment variable by 3 (step size is 3)

Variable ← Variable + 3

Example

count ← count+3 (can be used for a table of 3)

**Similarly students should be able to write statements to increment any step size.

Teacher : Shyam Subrahmanya 15 | P a g e


P2 Computer Science 9618

Totaling
(step size is variable i.e. varying every time)

Variable1 ← Variable1 + Variable2

Example

Total ← Total + number

Subtraction Statements (examples)

Num ← Num -2 …deduct 2 from a variable

Total← Total - ((20/100)*Total) …deduct 20% from a variable

Other examples of statements


NetTotal ← Total - ((20/100)*Total …difference assigned to a new variable

Duration ← TimeOut – TimeIn …difference of 2 other variables

NetTotal ← Total-Discount …difference of 2 other variables

Teacher : Shyam Subrahmanya 16 | P a g e


P2 Computer Science 9618

INPUT and OUTPUT (Pseudocode)


INPUT Name

(No space in identifier; identifiers cannot start with a number)

OUTPUT "Your name is", Name

Prompt & Input (Pseudocode)

Method 1

Output “Enter Marks” //Prompt

Input Marks //Input

Method 2

Input “Enter Marks”, Marks

Teacher : Shyam Subrahmanya 17 | P a g e


P2 Computer Science 9618

Control Structures
There are 3 Control Structures

1. Sequence (One statement after another)


2. Selection (When you have choices and you must select one option)
3. Iteration (also called repetition ; when same thing needs to be done multiple times)

Formats of Control Structures

Sequence
Example:

Statement 1

Statement 2

Statement 3

PSEUDOCODE EXAMPLE

DECLARE A : INTEGER

DECLARE B: INTEGER

INPUT A

INPUT B

OUTPUT A+B

Teacher : Shyam Subrahmanya 18 | P a g e


P2 Computer Science 9618

Selection
When you have choices and you have to make a selection.

 If _Then_ EndIf
If is usually used when there are 2 choices to choose from (this is not a rule, only preferred).

 Case Structure
Case is used when there are more than 2 choices to choose from. Case gives a shorter and easier
code (this is not a rule, only preferred).

Selection –IF
Pseudocode

Teacher : Shyam Subrahmanya 19 | P a g e


P2 Computer Science 9618

Pseudocode Selection- Case

Teacher : Shyam Subrahmanya 20 | P a g e


P2 Computer Science 9618

Pseudocode

THEN

On a new line

SEPARATE IF example

Teacher : Shyam Subrahmanya 21 | P a g e


P2 Computer Science 9618

NESTED IF example

Teacher : Shyam Subrahmanya 22 | P a g e


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 23 | P a g e


P2 Computer Science 9618

Pseudocode CASE

Teacher : Shyam Subrahmanya 24 | P a g e


P2 Computer Science 9618

Pseudocode CASE

DECLARE grade: CHAR DECLARE mark: INTEGER DECLARE choice: STRING

CASE of grade CASE of mark CASE of choice

‘A’: Output “Excellent” 90 to 100: Output “Excellent” “Apple”: Output “Very Healthy”

‘B’: Output “good” 30 to 89: Output “good” “Candies”: Output “unhealthy”

‘C’: Output “poor” 0 to 29: Output “poor” “Meat”: Output “Healthy”

OTHERWISE output ”invalid OTHERWISE output ”invalid OTHERWISE output ”invalid


entry” entry” entry”

ENDCASE ENDCASE ENDCASE

*Note: Otherwise is optional; but It is good to use otherwise to validate input.

Variations of case structure

(Example channels) (Example marks)

Case Channels of Case Marks of

“Documentary”: <50:

”Movies”: 50 to 80:

“Drama”: >80:

Teacher : Shyam Subrahmanya 25 | P a g e


P2 Computer Science 9618

Multiple cases in one statement

CASE OF Speedometer of CASE OF Grade

1,2,3,4 : speed←”slow” ‘A’, ‘B’: Output “ good result ”

5,6,7: speed← “Medium” ‘C’, ‘D’: Output “Average result”

8,9: speed ←”fast” ‘E’, ‘F’: Output “Poor result”

More than one statement can also be written for each case
Comparison between IF and CASE

Example: Enter grades of 8 students and output the corresponding remark according to the table
given. Also output the number of students who got A, B and C respectively.

Grade Remark

A Excellent

B Good

C poor

Teacher : Shyam Subrahmanya 26 | P a g e


P2 Computer Science 9618

//include declarations

count ←0

Answer: countA←0

CountB←0
//include declarations
CountC←0
count ←0
WHILE count<8
countA←0
INPUT grade
CountB←0
Count←count+1
CountC←0
IF grade=’A’
WHILE count<8
THEN
INPUT grade
OUTPUT “Excellent”
Count←count+1
countA←countA+1
CASE of grade
ELSE
‘A’: Output “Excellent”
If grade=’B’
countA←countA+1
THEN
‘B’: Output “good”
OUTPUT “good”
countB←countB+1
countB←countB+1
‘C’: Output “poor”
ELSE
countC←countC+1
IF grade =’C’
OTHERWISE OUTPUT ”invalid entry”
THEN
ENDCASE
Output “poor”
ENDWHILE
countC←countC+1
OUTPUT CountA, CountB,CountC
ENDIF

ENDIF

ENDIF

ENDWHILE
Teacher : Shyam Subrahmanya 27 | P a g e
OUTPUT CountA, CountB,CountC
P2 Computer Science 9618

Q. a) Input heights of 20 students using For loop. Output the corresponding remark using CASE
(Use Pseudocode). b) Rewrite the code using nested IF
Height Remark

1.0 to 3.9 short

4.0 to 6.5 good

More than 6.5 Very Tall

//INCLUDE DECLARATIONS HERE //INCLUDE DECLARATIONS HERE

FOR Count← 1 to 20 FOR Count← 1 to 20

INPUT height INPUT height

CASE OF height IF height>=1.0 AND height <= 3.9


THEN
1.0 to 3.9: Output “short”
OUTPUT “short”
4.0 to 6.5: Output “good”
ELSE
> 6.5: Output “Very Tall”
IF height>=4.0 AND height <= 6.5
OTHERWISE output ”invalid
entry” THEN

OUTPUT “good”
ENDCASE
ELSE
NEXT
IF height > 6.5
THEN
OUTPUT “Very Tall”
ELSE

OUTPUT ”invalid entry”


END IF
END IF
END IF
ENDFOR

Teacher : Shyam Subrahmanya 28 | P a g e


P2 Computer Science 9618

CASE STRUCTURE
Q1.

Pseudocode

DECLARE Marks : Integer

INPUT Marks

CASE OF Marks

< 40 :OUTPUT("Grade is U")

40 TO 60 :OUTPUT("Grade is C")

61 TO 80 :OUTPUT("Grade is B")

81 TO 100 :OUTPUT("Grade is A")

OTHERWISE OUTPUT(“Invalid
Entry”)

ENDCASE

Teacher : Shyam Subrahmanya 29 | P a g e


P2 Computer Science 9618

Q2.

PSEUDODCODE

Easier to use the following syntax

40 TO 49

But the following is also acceptable

>= 40 and <50

Teacher : Shyam Subrahmanya 30 | P a g e


P2 Computer Science 9618

Flowchart CASE STRUCTURE

ITERATION

Teacher : Shyam Subrahmanya 31 | P a g e


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 32 | P a g e


P2 Computer Science 9618

Iteration
Pseudocode

Teacher : Shyam Subrahmanya 33 | P a g e


P2 Computer Science 9618

FOR LOOP with step size


DECLARE value : INTEGER

FOR value  10 To 0 Step -2


OUTPUT value
NEXT

DECLARE value : REAL

FOR value  10 To 0 Step -0.5


OUTPUT value
NEXT

DECLARE value : INTEGER

FOR value  0 To 10 Step 3


OUTPUT value
NEXTFOR

Teacher : Shyam Subrahmanya 34 | P a g e


P2 Computer Science 9618

Types of loops
For_Next loop

 For is a count-controlled loop


 Set number of repetitions

Repeat _Until Loop

 Repeat…Until is a Post-Condition loop


 In Repeat _Until loop must execute at least once.

As long as the condition is false, it keeps looping. If the condition never becomes true, it will result
in an infinite loop.

While _End While Loop

 While ..…EndWhile is a Pre-condition Loop


 In While _End while loop may never execute (if the condition is false in the first
iteration)

As long as the condition is true, it keeps looping. If the condition never becomes false, it will result
in an infinite loop.

Teacher : Shyam Subrahmanya 35 | P a g e


P2 Computer Science 9618

Comparison between While, Repeat and For loop (Pseudocode)

Example : Write pseudocode to input 5 numbers, find the total and output the sum.

DECLARE count :INTEGER DECLARE count :INTEGER DECLARE count :INTEGER

DECLARE total : INTEGER DECLARE total : INTEGER DECLARE total : INTEGER

DECLARE number :INTEGER DECLARE number :INTEGER DECLARE number :INTEGER

count←0 count←0 total←0

total←0 total←0 number←0

WHILE count<5 REPEAT No need of

INPUT number INPUT number Count←count+1

count ← count+1 count ← count+1

total ← total + number total ← total + number FOR count ←1 TO 5

INPUT number

ENDWHILE UNTIL count = 5 total ← total + number

OUTPUT total OUTPUT total ENDFOR count

OUTPUT total

ENDFOR count
Both are acceptable
ENDFOR
Teacher : Shyam Subrahmanya 36 | P a g e
P2 Computer Science 9618

Loop for 5 times. Multiple ways of writing the loop

-----------------------------------------

COUNT 0

REPEAT

COUNT COUNT+1

UNTIL COUNT>=5

-----------------------------------------

COUNT 0

REPEAT

COUNT COUNT+1

UNTIL COUNT=5

-----------------------------------------

COUNT 1

REPEAT

COUNT COUNT+1

UNTIL COUNT=6

-----------------------------------------

COUNT 0

REPEAT

COUNT COUNT+1

UNTIL COUNT>4

-----------------------------------------

Teacher : Shyam Subrahmanya 37 | P a g e


P2 Computer Science 9618

'Find Minimum & Maximum


DECLARE max, min, count, mark : INTEGER

max  0
min  100
mark  0

WHILE count < 6


OUTPUT "enter mark"
INPUT mark

count  count + 1

IF mark < min


THEN
min  mark
ENDIF

IF mark > max


THEN
max  mark
ENDIF

ENDWHILE
OUTPUT ("min is " & min)
OUTPUT("max is " & max)

Trace Table
Input values are 4, 3, 6, 9, 2, 1

count mark max min output

//Method 2 - min and max can be initialized with the first input

Teacher : Shyam Subrahmanya 38 | P a g e


P2 Computer Science 9618

Practice questions

Q1) Input ages of 5 students. Find and output the youngest student’s age (use for loop).

Q2) Input marks for 7 students (use while loop). Find and output

 the average marks


 total marks

Q3) Input names of 5 students

Find and output name of the last student.

Q4) Input rents of 8 houses. Find and output the

 lowest rent
 highest rent
 average rent

Q5)

 Prompt the user to enter how many students there are in a class.
 Input marks of all the students
 Output the total marks

Hint:

INPUT students

FOR count =1 to students

Teacher : Shyam Subrahmanya 39 | P a g e


P2 Computer Science 9618

Q6) Input heights of 8 students

 Output total height


 Maximum height
 Minimum height
 Average height

Q7) Input prices of 6 items. Use while loop.

 Find and output the total bill


 Find and output how many prices were greater than $100
 Find and output the percentage of items that were greater than $100

Q8) Input prices of 6 items .Find and output the total bill (use REPEAT LOOP)

Rogue value
is used to terminate the loop. This should be a value other than the possible valid inputs.
This is usually used when it is not specified how many times the loop should repeat.

We cannot use FOR loop in rouge value.

Teacher : Shyam Subrahmanya 40 | P a g e


P2 Computer Science 9618

Q. Input Numbers until -1 has been entered. Output the minimum number.

a) Using while loop


DECLARE Min, Number : INTEGER

Min100

INPUT Number One input before WHILE


and one input before
WHILE Number < > -1
ENDWHILE so that rouge
IF Number < Min value is not processed.
THEN
Min  Number
ENDIF

INPUT Number

ENDWHILE

OUTPUT ( “Min is ” & Min)

Note: While loop may not execute even once. Repeat loop will execute at least once.

(include prompts in these solutions)

b) Using REPEAT
DECLARE Min, Number : INTEGER

Min100

INPUT Number

REPEAT

IF Number < Min


THEN
Min  Number
ENDIF

INPUT Number
UNTIL NUMBER = -1

OUTPUT ( “Min is ” & Min)

Teacher : Shyam Subrahmanya 41 | P a g e


P2 Computer Science 9618

Practice Rogue value


Q1. Input grades of students until z has been entered. Count and output how many times A* has
been entered.

Q2. Input prices of items until -999 has been entered. Output the lowest price.

Q3. Input marks of students until a terminating value has been entered. Find and output the
average marks. Choose an appropriate rogue value.

Example 1: Input a word of any length terminated by a rogue value “@”. Output the length
of the word. Pseudocode.

Ans.

//include declarations

length ← 0

char ← “ ”

INPUT char

WHILE char < > ‘@’


Input char has to be
length ← length +1 placed at the bottom
of the loop
INPUT char

ENDWHILE

OUTPUT length

Teacher : Shyam Subrahmanya 42 | P a g e


P2 Computer Science 9618

Case & Rogue value application

Q1. A shop sells books, maps and magazines. Each item is identified by a unique 4 – digit code.
All books have a code starting with a 1, all maps have a code starting with a 2 and all magazines
have a code beginning with a 3. The code 9999 is used to end the program. Write an algorithm
using pseudocode which input the codes for all items in stock and outputs the number of books,
maps and magazine in stock. Include any validation checks necessary.

(NOTE: A 4-digit code implies all books have a code lying between 1000

and 1999, all maps have a code lying between 2000 and 2999 and all

magazines a code lying between 3000 and 3999. Anything outside this range is an error)

Ans:

//include declarations

Books←0

maps←0

magazines←0

Input code

While code < > 9999 Do

CASE OF code

1000 to 1999: Books←Books+1

2000 to 2999: Maps←Maps+1

3000 to 3999: Magazines←Magazines+1

OTHERWISE OUTPUT “Invalid Entry”

ENDCASE

Input code

End while

OUTPUT Books, Maps, Magazines

Teacher : Shyam Subrahmanya 43 | P a g e


P2 Computer Science 9618

Iteration using rouge value

'Menu driven program

PROCEDURE multiply(x : INTEGER, y : INTEGER)


OUTPUT(x * y)
ENDPROCEDURE

PROCEDURE divide(x : INTEGER, y : INTEGER)


OUTPUT(x / y)
ENDPROCEDURE

PROCEDURE add(x : INTEGER, y : INTEGER)


OUTPUT (x + y)
ENDPROCEDURE

PROCEDURE subtract(x : INTEGER, y : INTEGER)


OUTPUT (x - y)
ENDPROCEDURE

PROCEDURE Main()
DECLARE choice : CHAR

REPEAT
OUTPUT("Enter M for Multiplication, D for Division")
OUTPUT("S for subtraction, A for Addition ")

INPUT choice
Case OF choice
‘M’: CALL multiply(5, 3)
‘A’: CALL add(5, 3)
‘D’: CALL divide(5, 3)
‘S’: CALL subtract(5, 3)
OTHERWISE
OUTPUT "invalid entry"
ENDCASE

OUTPUT "do you want to continue, Y/N"


INPUT choice

Until choice = ‘N’

ENDPROCEDURE

Teacher : Shyam Subrahmanya 44 | P a g e


P2 Computer Science 9618

Nested structures Pseudocode

NOTE:

ELSE IF on the same line should be avoided.

Nested IF

IF ….

IF…..

…………………..

END IF

END IF

Teacher : Shyam Subrahmanya 45 | P a g e


P2 Computer Science 9618

VB code

Nested For

FOR ROW= 1 TO 5

FOR COL= 1 TO 8

…………………

NEXT COL

NEXT ROW

Nested Loop

WHILE COUNT <4

Do

………………………….

LOOP UNTIL TEMP < 0

END WHILE

Teacher : Shyam Subrahmanya 46 | P a g e


P2 Computer Science 9618

Pseudocode
Note: It is compulsory to initialize counters, totals, min and max.

When to use ← and =


= is called a Relational operator

← is called an Assignment operator

= is used to check equality


In conditions we use =

Examples

 IF Num=0

 While Found= False…..

Repeat

….

 Until Found=True

← is used for Assignment


When we want to assign a value, we use ←

Num←0

Found←True

Min←100

Max←Num

Teacher : Shyam Subrahmanya 47 | P a g e


P2 Computer Science 9618

In pseudocodes
count←5 statement is correct
If count←5 condition is incorrect

If count=5 correct = is known as a relational operator


If count←5 incorrect ← is known as an assignment operator

Assignment arrow cannot be used in a condition.


IF condition
WHILE condition
UNTIL condition

A condition always evaluates to TRUE/FALSE.

Teacher : Shyam Subrahmanya 48 | P a g e


P2 Computer Science 9618

ASCII Character Codes (0 through 127)

0 N/A 32 [space] 64 @ 96 `
1 N/A 33 ! 65 A 97 a
2 N/A 34 " 66 B 98 b
3 N/A 35 # 67 C 99 c
4 N/A 36 $ 68 D 100 d
5 N/A 37 % 69 E 101 e
6 N/A 38 & 70 F 102 f
7 N/A 39 ' 71 G 103 g
8 (backspace) 40 ( 72 H 104 h
9 (tab) 41 ) 73 I 105 i
10 (line feed) 42 * 74 J 106 j
11 N/A 43 + 75 K 107 k
12 N/A 44 , 76 L 108 l
13 (carriage 45 - 77 M 109 m
return)
14 N/A 46 . 78 N 110 n
15 N/A 47 / 79 O 111 o
16 N/A 48 0 80 P 112 p
17 N/A 49 1 81 Q 113 q
18 N/A 50 2 82 R 114 r
19 N/A 51 3 83 S 115 s
20 N/A 52 4 84 T 116 t
21 N/A 53 5 85 U 117 u
22 N/A 54 6 86 V 118 v
23 N/A 55 7 87 W 119 w
24 N/A 56 8 88 X 120 x
25 N/A 57 9 89 Y 121 y
26 N/A 58 : 90 Z 122 z
27 N/A 59 ; 91 [ 123 {
28 N/A 60 < 92 \ 124 |
29 N/A 61 = 93 ] 125 }
30 N/A 62 > 94 ^ 126 ~
31 N/A 63 ? 95 _ 127 N/A

Teacher : Shyam Subrahmanya 49 | P a g e


P2 Computer Science 9618

String operations
EXAMPLE : SIGN UP ACCOUNTS

First Name Ali LastName Sarim

SUGGESTED USER IDs are as follows

AliSarim

SarimA

Ali.S

Ali.Sa

Teacher : Shyam Subrahmanya 50 | P a g e


P2 Computer Science 9618

String operations
School Time
Extract from left, right or mid 4321
Evaluate the following

LEFT("School Time", 3)

RIGHT("School Time", 4)

MID("School", 4,3)

MID (STRING, starting position, how many characters to extract)

MID("School", 4,3)

"C" & MID("School", 4,3)

TO_UPPER("temp")

TO_LOWER("CaMeL CaSe")

Concatenation
Joining two strings
& + operators are used for
concatenation
//Prefer using & instead of +

Teacher : Shyam Subrahmanya 51 | P a g e


P2 Computer Science 9618

String operations
Page 260 text book

'Extract from left , right or mid


DECLARE str1 : STRING

str1  "Pakistan"

OUTPUT(LEFT(str1, 3))
OUTPUT (RIGHT(str1, 4))
OUTPUT (MID(str1, 2, 5))

OUTPUT (LEFT("hello", 4))


OUTPUT (RIGHT("Cat", 2))
OUTPUT (MID(LEFT("Karachi", 5), 2, 3))
OUTPUT ((MID(LEFT("Karachi", 5), 2, 3)) & "five")
OUTPUT (MID("wi fi", 2, 3))

OUTPUT (TO_UPPER(str1))
OUTPUT (TO_LOWER(str1))

OUTPUT (CHR(65))
OUTPUT (CHR(68))

DECLARE str1,str2 :STRING

INPUT str1
str2  Left(str1, 3))

TO_UPPER and TO_LOWER are used to convert to


STRINGS TO uppercase and lowercase

str2 TO_UPPER(str1)
str2  TO_LOWER(str1)

LCASE and UCASE are used to convert to


CHARACTER DATA TYPE TO uppercase and lowercase

DECLARE LETTER1, LETTER2 : CHAR


INPUT LETTER1
LETTER2  LCASE(LETTER1)
LETTER2  UCASE(LETTER1)

Teacher : Shyam Subrahmanya 52 | P a g e


P2 Computer Science 9618

//to print alphabets


DECLARE count : Integer
For count  65 To 90
OUTPUT(CHR(count))
ENDFOR

Integer data type result

DECLARE str2 : STRING


Str2 "Karachi City"

OUTPUT(LENGTH(str2)) // 12- LENGTH OF THE STRING IS DISPLAYED.


//CONSIDER SPACE AS A VALID CHARACTER

OUTPUT(ASC(str2)) // ASCII VALUE OF THE LEFT MOST CHARACTER IS DISPLAYED

9608/21/M/J/16

Answer

Teacher : Shyam Subrahmanya 53 | P a g e


P2 Computer Science 9618

Q1. Write a Procedure DISPLAY ( ) that takes EmployeeCode as a string parameter. It extracts and
outputs the ID, Department and Name. EmployeeCode follows the following format:

 3 digits of ID
 4 characters of Department
 Name of variable length

<ID><Department><Name>

Example 876ACCTSamad

Answer

PROCEDURE DISPLAY(EmployeeCode : STRING)

DECLARE ID : STRING
DECLARE Department : STRING
DECLARE Name : STRING

ID  LEFT(EmployeeCode, 3)
Department  MID(EmployeeCode, 4, 4)
Name  RIGHT(EmployeeCode, LENGTH(EmployeeCode) - 7)

OUTPUT ID
OUTPUT Department
OUTPUT Name

ENDPROCEDURE

(B) Write the corresponding call

CALL DISPLAY("876ACCTHina")

Teacher : Shyam Subrahmanya 54 | P a g e


P2 Computer Science 9618

Extract each character from a string


DECLARE ThisString :STRING
DECLARE ThisChar : CHAR
DECLARE count : INTEGER

ThisString  "hello"

'Method 1 (commonly used IN MARKING KEYS)


For count  1 To LENGTH(ThisString)
ThisChar = MID(ThisString, count, 1)
OUTPUT ThisChar
Next

'Method 2 ( NOT common)

//Count starts with 1 in Pseudocode. Works like an array of characters.

For count = 1 To Len(ThisString)


ThisChar = ThisString(count)
Console.WriteLine(ThisChar)

Next

Output would be

Teacher : Shyam Subrahmanya 55 | P a g e


P2 Computer Science 9618

Validation to check if ThisChar is a digit

If ThisChar >= ‘0’ And ThisChar <= ‘9’

Validation to check if ThisChar is a lower case letter

If ThisChar >= ‘a’ And ThisChar <= ‘z’

Validation to check if ThisChar is an upper case letter

If ThisChar >= ‘A’ And ThisChar <= ‘Z’

Q How many digits are there in ThisString?


DECLARE ThisString : STRING
DECLARE ThisChar : CHAR
DECLARE counter : INTEGER
DECLARE count : INTEGER

ThisString  "hello369"

counter  0

FOR count  1 To LENGTH(ThisString)


ThisChar  Mid(ThisString, count, 1)

IF ThisChar >= ‘0’ And ThisChar <= ‘9’


THEN
counter = counter + 1
ENDIF
ENDFOR

OUTPUT("number of digits " & counter)

Practice question

Write a procedure Validate( ) that takes ThisString as a parameter. It counts and outputs
the number of digits, lower case and upper case characters.

Teacher : Shyam Subrahmanya 56 | P a g e


P2 Computer Science 9618

Pseudocode_Strings
9608/21/M/J/17

Teacher : Shyam Subrahmanya 57 | P a g e


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 58 | P a g e


P2 Computer Science 9618

Past Paper Question

Teacher : Shyam Subrahmanya 59 | P a g e


P2 Computer Science 9618

FUNCTION ValidatePassword ( Pass : STRING) RETURNS BOOLEAN

DECLARE Count, CountD, CountU, CountL, Other : INTEGER

DECLARE ThisChar : Char

DECLARE Result : BOOLEAN

CountU 0

CountL  0

CountD 0

Other  0

FOR Count 1 TO LENGTH ( Pass)

ThisChar MID(Pass, Count,1)

IF ThisChar > = ‘0’ AND ThisChar<= ‘9’

THEN

CountD CountD+1

ELSE

IF ThisChar > = ‘a’ AND ThisChar<= ‘z’

THEN

CountL CountL+1

ELSE

IF ThisChar > = ‘A’ AND ThisChar<= ‘Z’

THEN

CountU CountU+1

ELSE

Other Other + 1

ENDIF

ENDIF

ENDIF

ENDFOR continued…

Teacher : Shyam Subrahmanya 60 | P a g e


P2 Computer Science 9618

IF CountD >= 3 AND CountL >=2 AND CountU>=2 AND Other=0

THEN

Result  TRUE

ELSE

Result  FALSE

ENDIF

RETURN Result

ENDFUNCTION

Teacher : Shyam Subrahmanya 61 | P a g e


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 62 | P a g e


P2 Computer Science 9618

9608/22/M/J/17

Errors in the marking key are as follows:

 LEN should be written as LENGTH built in function


 ValidateRegistration  TRUE should not be at the top of the code.
 IF NextChar <’A’ AND NextChar >’Z’ should be IF NextChar <’A’ OR NextChar >’Z’
 IF NextChar <’0’ AND NextChar >’9’ should be IF NextChar <’0’ OR NextChar >’9’

Answer

FUNCTION ValidateRegistration ( Registration : STRING) RETURNS BOOLEAN

DECLARE L, UCount, NumCount, n : INTEGER

DECLARE NextCHar : CHAR

DECLARE Result : BOOLEAN

Teacher : Shyam Subrahmanya 63 | P a g e


P2 Computer Science 9618

Result TRUE
L  LENGTH (Registration)
IF L <6 OR L > 9
THEN
Result FALSE
ELSE
FOR n 1 to 3
NextChar  MID (Registration, n, 1)
IF NextChar <’A’ OR NextChar >’Z’
THEN
Result  FALSE
ENDIF
ENDFOR
FOR n 4 to 5
NextChar  MID (Registration, n, 1)
IF NextChar <’0’ OR NextChar >’9’
THEN
Result  FALSE
ENDIF
ENDFOR
FOR n 6 to LENGTH(Registration)
NextChar MID (Registration, n ,1
IF NextChar <’A’ OR NextChar> ‘Z’
THEN
Result FALSE
ENDIF
ENDFOR
ENDIF
RETURN Result
ENDFUNCTION

Teacher : Shyam Subrahmanya 64 | P a g e


P2 Computer Science 9618

ISNUM is a built-in function that returns TRUE if the argument is numeric otherwise returns FALSE.
Example

Str1  ”87534”

IF ISNUM(Str1)

THEN

OUTPUT “The string consists of digits only”

ENDIF

NOTE:

Str2  “7@GF”

IF Str2 = TO_UPPER (Str2)

Cannot be used to validate if the string is in uppercase or not because it will not be able to identify
digits and symbols.

Practice Questions
9608/22/M/J/17 Q3. Fill in the blanks
Q6 9608/21/M/J/16 Trace table

Teacher : Shyam Subrahmanya 65 | P a g e


P2 Computer Science 9618

SPECIMEN INSERT P2

Teacher : Shyam Subrahmanya 66 | P a g e


P2 Computer Science 9618

Pg. 261 text book


DECLARE num :INTEGER
Truncating numbers
Instead of rounding, sometimes we just want the whole number part of a real number.
This is known as 'truncation'.
num  INT (76.55) // 76
Converting a string to a number
Sometimes a whole number may be held as a string. To use such a number in a calculation,
we first need to convert it to an integer. For example, these functions return the integer value
5 from the string “5”. Works for both integer and real data type.

num  STRING_TO_NUM (“5.95”) //5.95


Date and Time data type

DECLARE MyDate :DATE

MyDate  #12/05/2020#

OUTPUT
Page 246 text book

In pseudocode, we can indicate whether a new line should be output at the end by a comment at the
end of the statement.

OUTPUT (“Hello”) // newline


Hello
OUTPUT (“World”)
World

OUTPUT(“Hello”) //no new line


HelloWorld
OUTPUT(“World”)

Teacher : Shyam Subrahmanya 67 | P a g e


P2 Computer Science 9618

Random Number Generator


RANDOMBETWEEN(min,max)
// generates a random integer between the integers min and max (inclusive)

Q. Generate 10 random numbers between 1 and 5

Num ← RANDOMBETWEEN (1,5)

//Note 1 and 5 are both inclusive

RND( )

// Always generates a random real number between 0 and 1.

Num← RND( )

Teacher : Shyam Subrahmanya 68 | P a g e


P2 Computer Science 9618

Subroutines
9608/22/M/J/19
2 (a) (i) Procedures and functions are examples of subroutines.
State a reason for using subroutines in the construction of an algorithm.
...........................................................................................................................................
..................................................................................................................................... [1]
(ii) Give three advantages of using subroutines in a program.
1 ........................................................................................................................................
...........................................................................................................................................
2 ........................................................................................................................................
...........................................................................................................................................
3 ........................................................................................................................................
.......................................................................................................................................[3]

Teacher : Shyam Subrahmanya 69 | P a g e


P2 Computer Science 9618

Subroutines/ Modularization

Definition
Programs are usually built up from small, self contained blocks of code called subroutines,
subprograms, procedures or modules.

It makes it easy for the programmer to write, test and debug code using modular approach.

Subroutines are of 2 types: functions and procedures


Predefined functions and procedures
Set of built-in subroutines that perform standard functions in a programming language
example MOD, INT.

Library routines
A LIBRARY ROUTINE is a set of programming instructions for a given task that is
already available for use. It is pre-tested and usually performs a task that is frequently
required. For example, the task ‘get time’ in the checking-for-the-alarm-time algorithm
would probably be readily available as a library routine.

Benefits of predefined functions/procedures or library routines:


 results in reusable codes
 A lot of programmer’s time is saved
 Already tested and debugged
User Defined functions / Built-in functions

Differences

• Built-in functions are made available by the programming language / already in the
system
• Built-in functions are ready made and tested
• User-defined functions can be modified // built-in cannot be modified
• User defined functions can be designed to meet the user's requirements
• User-defined functions can only be used in that program / module
Similarities
• They have an identifier name
• They return a value
• They have none, one or more arguments
• Both perform a specific task
• Both represent re-usable code
• Both are 'called'

Teacher : Shyam Subrahmanya 70 | P a g e


P2 Computer Science 9618

Procedure Vs Function
Page 262 ; 265

Subroutines are of 2 types- Procedure or Function

Procedure does not return values


Function returns exactly one value

Procedure Function
1 PROCEDURE Add(num1 : Integer, num2 : 1 FUNCTION Add(num1 : Integer, num2 : Integer) RETURNS
Integer) Integer

2 DECLARE Result :INTEGER 2 DECLARE Result :INTEGER

3 Result←num1+num2 3 Result←num1+num2

4 OUTPUT Result 4 OUTPUT Result

5 END PROCEDURE 5 RETURN Result

6 END FUNCTION

‘Call to a procedure ‘call to a Function

Call Add(4,7) Answer←Add(4,7)

Call Add(num1, num2) Answer←Add(num1,num2)

Call Add(x,y) OUTPUT (Add(4,7))

*changes are highlighted

NOTE
Line #1

 In procedure declaration keyword is PROCEDURE


 in function declaration keyword is FUNCTION

Teacher : Shyam Subrahmanya 71 | P a g e


P2 Computer Science 9618

 In procedure no return data type


 In function mention the return data type

Line # 5

 Procedure - No need of RETURN statement


 Function- RETURN Statement is required

 ENDPROCEDURE
 ENDFUNCTION

Subroutine Call

 Procedure- Use Keyword CALL


 Function- NO need of CALL ( output the returned value, assign it to a variable or use any other
suitable method).

Practice Questions
9608/21/M/J/18

9608/22/M/J/19

A procedure, CountLines(), is being written to count the number of lines in a text file. The
procedure will:

• take a filename as a string parameter

Teacher : Shyam Subrahmanya 72 | P a g e


P2 Computer Science 9618

Classwork
Write subroutine headers for the following

1.Function TEST takes a parameter MyCharacter of type char. it returns TRUE/FALSE.

2. Procedure PumpIN( ) that pumps in water in a swimming pool.

3. A subroutine Calculate( ) that returns the integer RESULT.

It takes three integer coordinates as parameter x, y and z.

Alternative method of returning a value


FunctionName  ValueToReturn

Instead of

RETURN ValueToReturn

FUNCTION Add(num1 : Integer, num2 : Integer) RETURNS FUNCTION Add(num1 : Integer, num2 : Integer) RETURNS

INTEGER INTEGER

DECLARE Result :INTEGER DECLARE Result :INTEGER

Result←num1+num2 Result←num1+num2

OUTPUT Result OUTPUT Result

RETURN Result Add  Result

END FUNCTION END FUNCTION

Teacher : Shyam Subrahmanya 73 | P a g e


P2 Computer Science 9618

Procedure

Pseudocode

Teacher : Shyam Subrahmanya 74 | P a g e


P2 Computer Science 9618

Function(returns exactly one value)


Pseudocode

Teacher : Shyam Subrahmanya 75 | P a g e


P2 Computer Science 9618

Passing parameters to subroutines


Page 267 text book

Subroutine Interface: The parameters being passed between the subroutine and the calling
program.

 Order of the parameters must be the same as the order of the arguments.
 Arguments and the corresponding parameters must have the same data types.
 The number of arguments sent must match with the number of parameters.

Arguments/ Parameters
When the main program calls a subroutine, the values being passed to the subroutine are
called arguments. In the subroutine the values are called parameters.

PROCEDURE Add (num1 : INTEGER, num2 : INTEGER)

// num1, num2 are parameter in the subroutine header

…….

ENDPROCEDURE

Corresponding call in another subroutine would be

CALL Add(x,y)

//x, y are arguments in the call

NOTE

x corresponds to num1 and y corresponds to num2.


Arguments and parameters must correspond to each other in terms of data types. Number of
arguments sent must be equal to number of parameters received.

Teacher : Shyam Subrahmanya 76 | P a g e


P2 Computer Science 9618

Errors

CALL Add( 3, “56”)

CALL Add( ‘a’, 45)

Data type of argument does not match with data type of parameters

[Extension: It is Runtime error]

CALL Add (45, 3, 78)

Number of arguments are not matching with number of parameters.

[Extension : It is a Syntax Error.]

Teacher : Shyam Subrahmanya 77 | P a g e


P2 Computer Science 9618

Q5. The company wants a program to output the total monthly sales for one of the
selected websites.

The programmer codes a function with the following function header:

FUNCTION MonthlyWebSiteSales(ThisMonth : INTEGER, ThisSite : CHAR) RETURNS


INTEGER

The function returns the total number of bicycles sold for the given month and website.
The function will use the following:

(i) Give the number of parameters of this function . ..............................................[1]

(ii) Some of the following function calls may be invalid.


Mark each call with:
• a tick (✓), for a valid call
• a cross (✗), for an invalid call
For any function calls which are invalid, explain why.

Teacher : Shyam Subrahmanya 78 | P a g e


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 79 | P a g e


P2 Computer Science 9618

Q. A string-handling function has been developed.

a) Label parts of the following function header

PUBLIC FUNCTION SSM(String1: STRING, String2 : STRING) RETURNS INTEGER


a b c d e

a____scope of function______ b___identifier, function name__

c__________paramete1_____ d_____data type of parameter1

e_________return data type

Teacher : Shyam Subrahmanya 80 | P a g e


P2 Computer Science 9618

Calling a Procedure (There is a single way of calling a procedure)

PROCEDURE MyProc( Para : INTEGER)

… …

ENDPROCEDURE

CALL MyProc( Num )

CALL MyProc(45)

FUNCTION MyNum ( Para: INTEGER) RETURNS INTEGER

…..

ENDFUNCTION

Different ways of Calling a Function


Function call is substituted by the value returned.

DECLARE Result : INTEGER

Result  MyNum( 23) //Assigning the return value to a variable

OUTPUT (MyNum( 78)) //outputting the return value

IF MyNum(45) >90 // using return value in a condition

Result  7 + MyNum(5) // use in a formula

Teacher : Shyam Subrahmanya 81 | P a g e


P2 Computer Science 9618

5 DATA SOURCES
Example: Output the double of Num. Value of Num can be received through 5 sources in our code.

1.USER INPUT

PROCEDURE DOUBLE()

DECLARE Num :INTEGER

OUTPUT “Enter number”

INPUT Num

OUTPUT Num*2

END PROCEDURE

2. Hardcode

PROCEDURE DOUBLE()

DECLARE Num :INTEGER

Num= 5

OUTPUT Num*2

END PROCEDURE

3. Global variable
//Some value has been set by other subroutines

DECLARE Num :INTEGER

PROCEDURE DOUBLE()

OUTPUT Num*2

END PROCEDURE

Teacher : Shyam Subrahmanya 82 | P a g e


P2 Computer Science 9618

4. Parameter passing
//Procedure is receiving the value of Num as a parameter

PROCEDURE DOUBLE( Num : INTEGER)

OUTPUT Num*2

END PROCEDURE

5. Read Value from a TEXT FILE

PROCEDURE DOUBLE()

DECLARE Num :INTEGER

DECLARE Data : STRING

OPENFILE (“TEST.txt” FOR READ)

READFILE (“TEST.txt” , Data)

Num← STRING_To_NUM(Data)

OUTPUT Num*2

CLOSEFILE(“TEST.txt”)

END PROCEDURE

Teacher : Shyam Subrahmanya 83 | P a g e


P2 Computer Science 9618

Parameter passing by value/ by reference

_________________________________________________________________________

Teacher : Shyam Subrahmanya 84 | P a g e


P2 Computer Science 9618

Text book page 269

Definition
By value:
– A copy of the variable itself is passed.
– leaving the variable in the calling program unaffected

By reference:
_The address of the variable is passed.

– Original value in the calling program is also changed when parameter


changed in called module.

According to CAIE outline: If the method for passing parameters is not specified, passing
by value is assumed.

Note that array arguments and user-defined type arguments should not be passed BYVAL
(because of their large size).

Also, using BYVAL or BYREF doesn't have any effect when the argument is a literal
constant--only when it's a variable.

Protection. In choosing between the two passing mechanisms, the most important criterion
is the exposure of calling variables to change.

The advantage of passing an argument ByRef:

 it eliminates the overhead of copying large amounts of data e.g. array


 is that the procedure can return a value to the calling code through that argument.

DISADVANTAGE OF by reference:

Weak security because procedure can modify the caller’s data at will, possibly changing
that data.

The advantage of passing an argument BYVAL

is that it protects a variable from being changed by the procedure.

Disadvantage of BYVAL:

Call by value is bad for performance if data being passed is large because making a copy of
that data takes time and consumes memory.

Teacher : Shyam Subrahmanya 85 | P a g e


P2 Computer Science 9618

Parameter Passing (pseudocodes)


To specify whether a parameter is passed by value or by reference, the keywords BYVALUE and BYREF
precede the parameter in the definition of the procedure. If there are several parameters, they should
all be passed by the same method and the BYVALUE or BYREF keyword need not be repeated.

If the method for passing parameters is not specified, passing by value is assumed.

If parameters are passed by reference (as in the above example), when the procedure is called an
identifier for a variable of the correct data type must be given (rather than any expression which
evaluates to a value of the correct type). A reference (address) to that variable is passed to the
procedure when it is called and if the value is changed in the procedure, this change is reflected in the
variable which was passed into it, after the procedure has terminated.

In principle, parameters can also be passed by value or by reference to functions and will operate in a
similar way. However, it should be considered bad practice to pass parameters by reference to a
function and this should be avoided. Functions should have no other side effect on the program other
than to return the designated value.

Teacher : Shyam Subrahmanya 86 | P a g e


P2 Computer Science 9618

BYVALUE
Consider the following program

PROCEDURE Test(BYVALUE x : INTEGER)

x  x + 1
OUTPUT(“x is ” & x)

ENDPROCEDURE

PROCEDURE LESSON( )
DECLARE a : Integer
a  2

CALL Test(a)

OUTPUT(“a is ” & a)

ENDPROCEDURE

OUTPUT IS

x is 3

a is 2

Teacher : Shyam Subrahmanya 87 | P a g e


P2 Computer Science 9618

BYREF
Consider the following program

PROCEDURE Test(BYREF y :INTEGER)

y  y + 1

OUTPUT(“y is ” & y)

ENDPROCEDURE

PROCEDURE LESSON( )

DECLARE b : Integer

b  3

CALL Test(b)

OUTPUT(“b is ” & b)

ENDPROCEDURE

OUTPUT IS

y is 4

b is 4

Teacher : Shyam Subrahmanya 88 | P a g e


P2 Computer Science 9618

Consider the following program

PROCEDURE Test(BYVAL x : INTEGER, BYREF y :INTEGER)

x  x + 1
y  y + 1
OUTPUT(“x is ” & x)
OUTPUT(“y is ” & y)

ENDPROCEDURE

PROCEDURE LESSON( )
DECLARE a : Integer
DECLARE b : Integer
a  2
b  3

CALL Test(a, b)

OUTPUT(“a is ” & a)
OUTPUT(“b is ” & b)

ENDPROCEDURE

OUTPUT IS

x is 3

y is 4

a is 2

b is 4

Teacher : Shyam Subrahmanya 89 | P a g e


P2 Computer Science 9618

SCOPE of a variable

Global Variables Vs Local Variables


Page 206, 266 text book

Global variables have global scope. They can be accessed from any subroutine. It is not a good
programming practice because data is insecure; any subroutine can change the global variable.

Global variables are written at the top of the code.

Local variables have local scope and they cannot be accessed from outside the current
subroutine. Data is more secure. They are accessible only within the module in which they are
declared.

Scope of a subroutine

Private Scope Vs Public Scope

Public scope of a subroutine means that it can be accessed from any module.

Private scope means that it can only be accessed from current module.

Example

PRIVATE FUNCTION TEST (Num: INTEGER)

PUBLIC FUNCTION TEST (Num: INTEGER)

Teacher : Shyam Subrahmanya 90 | P a g e


P2 Computer Science 9618

Arrays
1D Array page 212 text book

2D Array page 218 text book

Teacher : Shyam Subrahmanya 91 | P a g e


P2 Computer Science 9618

Arrays
 Array is a data structure.
 It is a set of continuous storage locations.
 One dimensional array is a linear list.
 All the elements in the array are of the same data type.
 A two dimensional array or double dimensional array is known as a table with
rows and columns.
 Index may start with 0 or 1
Explanation: In this example

Array name: Prices

Array size: 5

Index: 1 to 5

Array Data type: Real or currency

Array
Lower
Bound 1 46.87 element

2 21.50

3 43.00

4 67.00
Upper
5 24.00
Bound

Index/
Teacher : Shyam Subrahmanya 92 | P a g e
subscript
P2 Computer Science 9618

Finding total without array

Example : Write a pseudocode to input 5 prices. Find and output the average price.

DECLARE Total : CURRENCY

DECLARE Average : CURRENCY

DECLARE Prices: CURRENCY

DECLARE count : INTEGER

Total←0

Average←0
50
For count←1 to 5

Input Prices

Total←Total + Prices

ENDFOR
Variable Prices
Average←Total/5
Each new value overwrites
OUTPUT “Average is” , Average
the previous value

Teacher : Shyam Subrahmanya 93 | P a g e


P2 Computer Science 9618

Finding total with array

Example : Write a pseudocode to input 5 prices using an array Prices. Find and output the
average price.

DECLARE Prices: ARRAY [1: 5] OF CURRENCY

DECLARE Total : CURRENCY


50
DECLARE Average : CURRENCY

DECLARE count : INTEGER


20.5
Total←0 37.9
Average←0
60
For count←1 to 5

Input Prices[count] 25.3


Total←Total + Prices[count]

ENDFOR

Average←Total/5

OUTPUT “Average is” , Average


Array Prices

Values are stored in a list.

Values are not overwritten.

Teacher : Shyam Subrahmanya 94 | P a g e


P2 Computer Science 9618

Q. Input 1000 numbers in an Array using

 For
 While
 Repeat

Pseudocode Syntax

DECLARE Num: ARRAY [1:1000] OF INTEGER

DECLARE count : INTEGER

For count← 1 to 1000

Input Num[count]

ENDFOR

DECLARE Num: ARRAY [1:1000] OF INTEGER

DECLARE count : INTEGER

count←1

Repeat

Input Num[count]

count←count+1

Until count>1000

DECLARE Num: ARRAY [1:1000] OF INTEGER

DECLARE count : INTEGER

count←1

While count < =1000

Input Num[count]

count←count+1

ENDWHILE

Teacher : Shyam Subrahmanya 95 | P a g e


P2 Computer Science 9618

Q. Write statement to output the 7th number

Output Num[7]

Teacher : Shyam Subrahmanya 96 | P a g e


P2 Computer Science 9618

Initialization values can be different for different questions

Name[Index] ← “ ” (or Null)

Marks [Index] ← -1 ( or 0)

CheckerBoard [Index] ← “ ”

Number[Index] ← 0

Product[Index] ← 1

Teacher : Shyam Subrahmanya 97 | P a g e


P2 Computer Science 9618

1D Vs 2D Array

Pseudocode

DECLARE <identifier> : ARRAY[<lbound>:<ubound>] OF <datatype>


DECLARE <identifier> : ARRAY[<lbound1>:<ubound1>,<lbound2>:<ubound2>]
OF <datatype>
Example Single dimensional Array

DECLARE Numbers:ARRAY[1:5] OF INTEGER

1 D array is a list

Example double dimensional Array

DECLARE Sales: ARRAY[1:3,1:5] of real

2D array is a table/ grid

Teacher : Shyam Subrahmanya 98 | P a g e


P2 Computer Science 9618

Example 1 D array

DECLARE Num: ARRAY[1:5] OF Integer


DECLARE Item : INTEGER
DECLARE Index : INTEGER
DECLARE Found : BOOLEAN
DECLARE count : INTEGER

//initialize an array
FOR count  1 To 5
Num[count]  0
ENDFOR

//input in an array
FOR count  1 To 5
OUTPUT ("enter number " & count)
INPUT Num[count]
ENDFOR

//output from an array

FOR count  1 To 5
OUTPUT Num[count]
ENDFOR

'Search in an Array ..... Input what to search

Index  1
Found  False

OUTPUT "Enter Item to search"


INPUT Item

WHILE Index <= 5 AND Found=False

IF Num [Index] = Item


THEN
OUTPUT "item has been found at Index " , Index
Found  True
ENDIF

Index  Index + 1

ENDWHILE

IF Found = False
THEN
OUTPUT "Item is not in the list"
ENDIF

Teacher : Shyam Subrahmanya 99 | P a g e


P2 Computer Science 9618

Q1 a) Make array a global variable and use subroutines


DECLARE Num: ARRAY[1:5] OF Integer
DECLARE count : INTEGER

//initialize an array
PROCEDURE INITIALIZE()
FOR count  1 To 5
Num[count]  0
ENDFOR
ENDPROCEDURE

//input in an array
PROCEDURE ENTER()
FOR count  1 To 5
OUTPUT ("enter number " & count)
INPUT Num[count]
ENDFOR
ENDPROCEDURE

//output from an array


PROCEDURE DISPLAY( )
FOR count  1 To 5
OUTPUT Num[count]
ENDFOR
ENDPROCEDURE

Teacher : Shyam Subrahmanya 100 | P a g e


P2 Computer Science 9618

'Search in an Array ..... Input what to search

PROCDEURE SEARCH( )

DECLARE Item : INTEGER //LOCAL Variables


DECLARE Index : INTEGER
DECLARE Found : BOOLEAN

Index  1
Found  False

OUTPUT "Enter Item to search"


INPUT Item

WHILE Index <= 5 AND Found=False

IF Num [Index] = Item


THEN
OUTPUT "item has been found at Index " , Index
Found  True
ENDIF

Index  Index + 1

ENDWHILE

IF Found = False
THEN
OUTPUT "Item is not in the list"
ENDIF
ENDPROCEDURE

Teacher : Shyam Subrahmanya 101 | P a g e


P2 Computer Science 9618

Q1 b. Extend your algorithm to write a function SEARCH1( ) that takes parameter Item.
It returns the index at which the item was found in the array. Return -1 If the Item was not
found. Assume the array is a global variable.

FUNCTION Search1 (Item : INTEGER) RETURNS INTEGER

DECLARE Index :INTEGER


DECLARE Found :BOOLEAN
DECLARE IndexFound: INTEGER

Index  1
Found  False

WHILE Index <= 5 AND Found=False

IF Num [Index] = Item


THEN
OUTPUT "item has been found at Index " , Index
Found  True
IndexFound  Index
ENDIF

Index  Index + 1

ENDWHILE

IF Found = False
THEN
OUTPUT "Item is not in the list"
IndexFound  -1
ENDIF

RETURN IndexFound

ENDFUNCTION

(b) Write the corresponding function call to output the value returned. Assume 25 is the
argument.

OUTPUT Search1 (25)

(c) Write the corresponding function call. Assign the value returned to a new variable result.
Assume 25 is the argument.

DECLARE result: INTEGER


result  Search1(25)

Teacher : Shyam Subrahmanya 102 | P a g e


P2 Computer Science 9618

Homework
Modify the above PSEUDOCODE. Implement it as a menu driven program using VB.

Procedure Main ( ) // It will only have a single call


CALL Menu()
END PROCEDURE

PROCEDURE Menu( )

// OUTPUT the following menu

Enter I for Initialisation( )

Enter E for Enter( )

Enter D for Display( )

Enter R for Search using REPEAT loop

Enter F for Search using FOR loop

Enter W for Search using WHILE

//Use CASE structure to call the respective subroutine

//Use a rouge value loop to repeat the menu

ENDPROCEDURE

Home work Q5. 9608/21/M/J/15 Trace Table

Teacher : Shyam Subrahmanya 103 | P a g e


P2 Computer Science 9618

Single Vs Multiple Search results

Single Search Result


(Loop stops at the first occurrence of the match)

Item has been found at Index 3


1 14
2 25
3 70
Multiple Search Result
4 44
(Loop continues from lower bound to upper
5 70
Bound. It displays all the results where a match occurs.)

Item has been found at Index 3

Item has been found at Index 5

To implement multiple search, modify the search subroutine using one of the following

 Use simple FOR loop


 While Index <= 5 And Found =FALSE
 Until Index > 5 Or Found=TRUE

Case sensitive Vs Case insensitive Search

For a string data type array


Evaluate the following conditions

If “CAT”= “cat” FALSE

If “CAT” = “CAT” TRUE

Case insensitive search


IF TO_UPPER(words(Index)) = TO_UPPER(item)

If TO_LOWER(words(Index)) = TO_LOWER(item)

Case sensitive search


If ArrayName(Index) = item

Teacher : Shyam Subrahmanya 104 | P a g e


P2 Computer Science 9618

Practice Questions

Solve the following questions using Pseudocode.


(Refer to the search algorithm provided)

Q1. If the data item to be searched exists more than once in the array, which index number will
be displayed?
Q2. Rewrite the single search solution using REPEAT loop
Q3 a. Rewrite the solution given above for multiple search results using WHILE.
Q3 b. Rewrite the solution for multiple search results using REPEAT Loop
Q4. Rewrite the search program for multiple search results using FOR loop
Q5. Why is FOR loop not appropriate for single search result.
Q6. Rewrite the single search solution for searching item 20 in the array.

Q7. Given solution is for case sensitive search. Rewrite it for case insensitive search.
Assume Array StudentNames stores names of 6 students.
(Case insensitive search would consider “ALI”, “aLi” and “ali” as a match for “Ali”).

HINTS
Q1. Only the index corresponding to the first occurrence would be displayed.
Q2. Note the changes (Invert the condition)
WHILE Index <= 5 AND Found =FALSE
UNTIL Index > 5 OR Found=TRUE

Q3 a. Change the while condition to

While Index <= 5 And Not Found

Q3 b. UNTIL Index > 5

Q4. Make the following changes


Index  1

FOR Index 1 to 5
Index  Index + 1
ENDFOR

Q5. Inefficient. It continues the loop even after the item has been found.
Q6. This is an example of hard code. You do not need to take input from user now.
Q7. Make the following changes

Teacher : Shyam Subrahmanya 105 | P a g e


P2 Computer Science 9618

Pseudocode format - Search Procedure using While loop


Single search result

PROCEDURE Search1( )

DECLARE Index : INTEGER


DECLARE Found : BOOLEAN
DECLARE Item : INTEGER

Index  1
Found  False

OUTPUT "Enter Item to search"


INPUT Item

WHILE Index <= 5 AND Found=False

IF Num [Index] = Item


THEN
OUTPUT "item has been found at Index " , Index
Found  True
ENDIF

Index  Index + 1

ENDWHILE

IF Found = False
THEN
OUTPUT "Item is not in the list"
ENDIF

ENDPROCEDURE

Teacher : Shyam Subrahmanya 106 | P a g e


P2 Computer Science 9618

Pseudocode format - Search Procedure using Repeat loop


Single search result

PROCEDURE Search2( )

DECLARE Index : INTEGER


DECLARE Found : BOOLEAN
DECLARE Item : INTEGER

Index  1
Found  False

OUTPUT "Enter Item to search"


INPUT Item

REPEAT

IF Num [Index] = Item


THEN
OUTPUT "item has been found at Index " , Index
Found  True
ENDIF

Index  Index + 1

UNTIL Index > 5 OR Found=TRUE

IF Found = False
THEN
OUTPUT "Item is not in the list"
ENDIF

ENDPROCEDURE

Teacher : Shyam Subrahmanya 107 | P a g e


P2 Computer Science 9618

Pseudocode format - Search Procedure using FOR loop


(Multiple search results)

PROCEDURE Search3( )

DECLARE Index : INTEGER


DECLARE Found : BOOLEAN
DECLARE Item : INTEGER

Found  False

OUTPUT "Enter Item to search"


INPUT Item

FOR Index  1 to 5

IF Num [Index] = Item


THEN
OUTPUT "item has been found at Index " , Index
Found  True
ENDIF

ENDFOR

IF Found = False
THEN
OUTPUT "Item is not in the list"
ENDIF

ENDPROCEDURE

Teacher : Shyam Subrahmanya 108 | P a g e


P2 Computer Science 9618

Pseudocode Syntax

Example MyProgram is calling InitialiseArray

Subroutine Header

PROCEDURE InitialiseArray(Details:ARRAY OF String)


DECLARE Index : Integer
For Index ← 1 To 5
Details[Index]← ""
Parameters
ENDFOR
End PROCEDURE

PROCEDURE MyProgram()
DECLARE Details[5] : String

//Call to a procedure/Subroutine
Call InitialiseArray(Details)

End PROCEDURE
Arguments

Teacher : Shyam Subrahmanya 109 | P a g e


P2 Computer Science 9618

Practice questions
Q1.a) Write a subroutine MyMinimum( )

 That takes MyArray as a parameter


 Outputs the 2nd element from the array
 Returns the minimum value from the array

Main( )

 Declare array Weight of size 6 (Real data type)


 Input data in the array
 Call MyMinimum and send Weight as an argument.
 Output the minimum value

b) Edit Minimum ( ) and Main ( ) to make the following changes

Main( )

 Prompt and input the size of the array Weight


 Declare the array Weight
 Call MyMinimum. Send Weight and size as arguments.
 Output the minimum value

Teacher : Shyam Subrahmanya 110 | P a g e


P2 Computer Science 9618

Bubble sort

Text book page 215

Sorting

 Ascending order A-Z (default)


 Descending order Z-A

Teacher : Shyam Subrahmanya 111 | P a g e


P2 Computer Science 9618

Concept of PASSES

1
2
3
4
5

6
7

FOR Passes 1 TO Maxlndex – 1

ENDFOR

For 7 elements we need 6 passes

Note : Index 1 to 7
Total Number of elements 7

Required passes = Total elements -1 = 6

Because last element left is always sorted (there is no other element to compare it with).

Teacher : Shyam Subrahmanya 112 | P a g e


P2 Computer Science 9618

PASSES

Within each Pass, compare and swap

FOR Passes 1 TO Maxlndex – 1

FOR Index  1 TO n

//Compare and swap

ENDFOR

ENDFOR

Teacher : Shyam Subrahmanya 113 | P a g e


P2 Computer Science 9618

Within each Pass, compare and swap

FOR Passes 1 TO Maxlndex – 1

FOR Index  1 TO n

IF MyList[Index] > MyList[Index + 1]


THEN
Temp  MyList[Index]
MyList[Index]  MyList[Index + l]
MyList[Index+ 1]  Temp

ENDIF

ENDFOR

ENDFOR

Teacher : Shyam Subrahmanya 114 | P a g e


P2 Computer Science 9618

Compare only n-1 elements in the next pass

FOR Passes 1 TO Maxlndex – 1


……
……
n  n - 1 //code will only process n-1 elements in the next loop

ENDFOR

We initialize n with MaxIndex-1 = 6


Because for 7 elements, we have to compare 6 pairs in the first pass

Teacher : Shyam Subrahmanya 115 | P a g e


P2 Computer Science 9618

In the loop :
Compare 5 pairs in pass 2

Compare 4 pairs in pass 3, so on.

Teacher : Shyam Subrahmanya 116 | P a g e


P2 Computer Science 9618

n  Maxlndex – 1

FOR Passes 1 TO Maxlndex – 1

FOR Index  1 TO n

IF MyList[Index] > MyList[Index + 1]


THEN
Temp  MyList[Index]
MyList[Index]  MyList[Index + l]
MyList[Index+ 1]  Temp

ENDIF

ENDFOR

nn-1

ENDFOR

Inefficient algorithm because it will keep iterating even if the array is already
sorted.

Count controlled outer loop for passes should be replaced by a conditional loop.

Main idea is that if we have gone through the whole of the inner loop (one pass) without
swapping any values, we know that the array elements must be in the correct order.

Use a flag (Boolean variable) example NoMoreSwaps

NoMoreSwaps  TRUE
Indicates that there was not a single swap, thus the array has been sorted.

NoMoreSwaps  FALSE
Indicates that there was at least one swap, thus the array is still not sorted.

Teacher : Shyam Subrahmanya 117 | P a g e


P2 Computer Science 9618

n MaxIndex - 1
REPEAT
NoMoreSwaps  TRUE
FOR j  1 TO n
IF MyList [Index] > MyList [Index + l]
THEN
Temp  MyList[Index]
MyList[Index]  MyList[Index + 1]
MyList[Index + 1]  Temp
NoMoreSwaps  FALSE

ENDIF
ENDFOR
nn-1
UNTIL NoMoreSwaps = TRUE

Practice

Q3. 9608/22/O/N/17 bubble sort

Q3. 9608/21/O/N/17 bubble sort

Q5. 9608/22/O/N/15 trace table


1D array
Q3a,b 9608/21/M/J/19

Homework
9608/22/O/N/16 Q6 & Q4

Teacher : Shyam Subrahmanya 118 | P a g e


P2 Computer Science 9618

2D Array
[1] Name [2] Email [3] DOB [4] ID

[1] Ali abc@gmail.com 25/05/2010 D3452-B

[2] Saman xyz@gmail.com 15/07/2012 C3752-B

[3]

[4] John 65sdf7@gmail.com 15/05/2011 C3482-B

[5] Sahil weds@gmail.com 01/01/2016 C3432-V

2D Array

Details[1:5,1:4] indicates rows 1 to 5 and columns 1 to 4


Element 01/01/2019
1 row represents 1 record
At Index [5,3]
2D array is a grid or a Table
That is (Row,Column)
Data type

All elements in an array are of the same data type

Teacher : Shyam Subrahmanya 119 | P a g e


P2 Computer Science 9618

2D ARRAY
PROCEDURE TwoDArray()

DECLARE Num:ARRAY [1:2, 1:4] OF INTEGER

DECLARE Row : INTEGER


DECLARE Col : INTEGER
DECLARE Item : INTEGER
DECLARE Found : BOOLEAN

//initialize an array
FOR Row  1 To 2
FOR Col  1 To 4
Num[Row, Col]  0
ENDFOR
ENDFOR

//input in an array

For Row  1 To 2
For Col  1 To 4
OUTPUT("enter number")
INPUT Num[Row, Col]
ENDFOR
ENDFOR

//formatted output

FOR Row  1 To 2

FOR Col  1 To 4
OUTPUT(Num[Row, Col] & " ")
ENDFOR Col

//OUTPUT NEWLINE
ENDFOR Row

Teacher : Shyam Subrahmanya 120 | P a g e


P2 Computer Science 9618

//search in double dimensional array

Found  False
OUTPUT("Enter item to search")

INPUT Item

FOR Row  1 To 3
FOR Col  1 To 4

IF Num[Row, Col] = Item


THEN

OUTPUT("Item has been found at " & Row & " , " & Col)
Found  TRUE
EXIT PROCEDURE

ENDIF

ENDFOR Col
ENDFOR Row

IF Found = FALSE
THEN
OUTPUT("Item does not exist in the array")
ENDIF

ENDPROCEDURE

//Alternative correct solutions exist for search

Pseudocode- 2D array passed as a parameter


Parameter
//PROCEDURE header passing of 1D
and 2D array
PROCEDURE TEST(DETAILS:ARRAY OF String) is identical in
pseudocode.
//Call to a PROCEDURE

Call TEST(Details)

Teacher : Shyam Subrahmanya 121 | P a g e


P2 Computer Science 9618

//Global variable declarations


DECLARE ProductionData:ARRAY [1:4, 1:3] OF INTEGER

DECLARE Row : INTEGER


DECLARE Col : INTEGER

//output the production data of day3


PROCEDURE OUTPUT()

FOR Col  1 To 3
OUTPUT ProductionData [3, Col]
ENDFOR
ENDPROCDEURE

//Input the production data of Worker1 for all 4 days

PROCEDURE INPUT()

FOR Row  1 To 4
OUTPUT “Enter data”
INPUT ProductionData [Row, 1]
ENDFOR
ENDPROCDEURE

//OUTPUT the production data of Worker2 day3

PROCEDURE CELL()

OUTPUT ProductionData [3, 2]


ENDPROCDEURE

Teacher : Shyam Subrahmanya 122 | P a g e


P2 Computer Science 9618

Practice question: Q5 9608/23/M/J/15 Trace table (1D & 2D)

Teacher : Shyam Subrahmanya 123 | P a g e


P2 Computer Science 9618

File Operations
Files are permanent storage of data. Data is stored in the memory even after the program closes.

Arrays are temporary storage of data. Data is lost as soon as the program closes.

Teacher : Shyam Subrahmanya 124 | P a g e


P2 Computer Science 9618

File handling

File Operations –Pseudocode

WRITE

Program File

READ

DECLARE data : STRING


data ← "Hello"

//open file to write data on the file

OPENFILE("TESTFILE.txt" FOR WRITE)


WRITEFILE(“TESTFILE.txt” , data)
CLOSEFILE(“TESTFILE.txt”)

// Open file to append. Insert at the end of file.

OPENFILE("TESTFILE.txt" FOR APPEND)


WRITEFILE(“TESTFILE.txt” , data)
CLOSEFILE(“TESTFILE.txt”)

// Open file to read data from file.

OPENFILE("TESTFILE.txt" FOR READ)

WHILE NOT EOF(“TESTFILE.TXT”)


READFILE (“TESTFILE.txt”, data)
ENDWHILE
CLOSEFILE(“TESTFILE.txt”)

Teacher : Shyam Subrahmanya 125 | P a g e


P2 Computer Science 9618

Example1- Write data on file


Q. Write 4 items of data, entered by the user, onto the file.

DECLARE data : STRING


DECLARE count : INTEGER

OPENFILE("TESTFILE.txt" FOR WRITE)

FOR count  1 To 4
OUTPUT ("Enter data") 'prompt
INPUT Data

WRITEFILE(“TESTFILE.txt” , data)
ENDFOR

CLOSEFILE(“TESTFILE.txt”)

NOTE: In Output mode if a file already exists, it will be overwritten. If it does not exist, a new file
will be created automatically.
Open and close files are always outside the loop
If file is open in one mode it cannot be opened in another mode until it is closed.

Teacher : Shyam Subrahmanya 126 | P a g e


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 127 | P a g e


P2 Computer Science 9618

Example 2a- Append data


DECLARE Data : STRING
Data  "hello"

OPENFILE("TESTFILE.txt" FOR APPEND)


WRITEFILE(“TESTFILE.txt” , data)
CLOSEFILE(“TESTFILE.txt”)

Example 2b-Append Data in a loop


DECLARE Data : STRING

OPENFILE("TESTFILE.txt" FOR APPEND)

FOR count  1 To 3
OUTPUT("Enter data")
INPUT Data
//Append line at the end of file
WRITEFILE(“TESTFILE.txt” , data)

ENDFOR
CLOSEFILE(“TESTFILE.txt”)

Append means to add data to the end of file (Does not overwrite file)
If the file does not exist, a new file is created.
If the question does not say create a new file then go for the append mode.

Teacher : Shyam Subrahmanya 128 | P a g e


P2 Computer Science 9618

Example 3 – Read data from file

DECLARE data: STRING


OPENFILE("TESTFILE.txt" FOR READ)

WHILE NOT EOF(“TESTFILE.TXT”)


READFILE (“TESTFILE.txt”, data)
OUTPUT data
ENDWHILE
CLOSEFILE(“TESTFILE.txt”)

Note

If the file doesn’t exist, OPENFILE will give a run time error.
If file is already open in another mode, it should be closed first and
then opened FOR READ.

Teacher : Shyam Subrahmanya 129 | P a g e


P2 Computer Science 9618

Using 2 files
Read data from FileA
Convert the data into uppercase
Save the data in FileB

DECLARE data : STRING

OPENFILE("FileA.txt" FOR READ)


OPENFILE("FileB.txt" FOR WRITE)

WHILE NOT EOF(“FileA.TXT”)

READFILE (“FileA.txt”, data)


data  UCASE (data)
WRITEFILE(“FileB.txt” , data)

ENDWHILE

CLOSEFILE(“FileA.txt”)
CLOSEFILE(“FileB.txt”)

NOTE

We cannot edit or delete anything in a text file. In order to make changes or delete data, create
another file. Leave the original file unchanged.

Teacher : Shyam Subrahmanya 130 | P a g e


P2 Computer Science 9618

Rouge Value & File handling


DECLARE ID :STRING
DECLARE options : CHAR

OPENFILE("TESTFILE.txt" FOR WRITE)

REPEAT
OUTPUT("Enter ID")
INPUT ID
WRITEFILE(“TESTFILE.txt” , ID)
OUTPUT("Do you want to enter another ID? Enter N for no, press any
other key for Yes")
INPUT options

UNTIL options = ‘N’

CLOSEFILE(“TESTFILE.txt”)

Teacher : Shyam Subrahmanya 131 | P a g e


P2 Computer Science 9618

Menu driven file operations program. Assume FileName is a global variable.

DECLARE FileName : STRING //Global variable

PROCEDURE MENU( )

DECLARE choice : CHAR


DECLARE Data : STRING
DECLARE count : INTEGER

//Any subroutine can assign the value to the global variable


FileName  “Employee.txt”

REPEAT
OUTPUT("Enter R for Read data from file, Enter A for Append,")
OUTPUT("Enter W for Writing data, Enter E to end program ")

INPUT choice
CASE OF choice
‘W’: CALL WriteNow( )

‘A’: CALL AppendNow( )

‘R’: CALL ReadNow( )

‘E’: End // end program

OTHERWISE OUTPUT("invalid entry")

ENDCASE

UNTIL False //infinite loop

ENDPROCEDURE

//CONTINUED ON THE NEXT PAGE

Teacher : Shyam Subrahmanya 132 | P a g e


P2 Computer Science 9618

PROCEDURE ReadNow( )

DECLARE data: STRING

OPENFILE(FileName FOR READ)

WHILE NOT EOF(FileName)


READFILE (FileName, data)
OUTPUT data
ENDWHILE

CLOSEFILE FileName

ENDPROCEDURE

PROCEDURE AppendNow( )

DECLARE Data : STRING

OPENFILE(FileName FOR APPEND)

OUTPUT("Enter data")
INPUT Data
WRITEFILE(FileName, data)

CLOSEFILE FileName

ENDPROCEDURE

PROCEDURE WriteNow( )

DECLARE data : STRING

OPENFILE(FileName FOR WRITE)

OUTPUT ("Enter data")


INPUT Data

WRITEFILE(FileName , data)

CLOSEFILE FileName

ENDPROCEDURE

Teacher : Shyam Subrahmanya 133 | P a g e


P2 Computer Science 9618

PROCEDURE WriteOperation(FileName as STRING)

//Corresponding CALL is as follows

CALL WriteOperation ("Students.txt")

Teacher : Shyam Subrahmanya 134 | P a g e


P2 Computer Science 9618

9608/21/O/N/17

Teacher : Shyam Subrahmanya 135 | P a g e


P2 Computer Science 9618

2 different file structures


9608/21/O/N/16

ID 0198 indicates
string datatype
because of
leading zero

Teacher : Shyam Subrahmanya 136 | P a g e


P2 Computer Science 9618

Teacher : Shyam Subrahmanya 137 | P a g e


P2 Computer Science 9618

Q1.Use the file structure shown. (a) Write a procedure ReadNow( ) that takes FileName as a
parameter. It reads and outputs all the records from the text file. (b) Write a procedure AppendNow( )
that takes FileName as a parameter and inserts new record in the text file.

0198 (a)PROCEDURE ReadNow(FileName :STRING )


DECLARE ID: STRING
Onion DECLARE Description: STRING
DECLARE StrPrice :STRING
23.56 DECLARE Price:REAL
OPENFILE(FileName FOR READ)
2456
WHILE NOT EOF(FileName)
Mango READFILE (FileName, ID)
OUTPUT (“ID IS ” & ID)
34.99
READFILE (FileName, Description)
….. …. OUTPUT (“Desc is” & Description)

…. …… READFILE (FileName, StrPrice)


Price STRING_TO_NUM (StrPrice)
OUTPUT (“Price is ” & Price)

ENDWHILE
CLOSEFILE FileName

ENDPROCEDURE

(b)PROCEDURE AppendNow(FileName :STRING )

DECLARE ID: STRING


DECLARE Description: STRING
DECLARE Price: REAL

OPENFILE(FileName FOR APPEND)

OUTPUT("Enter ID")
INPUT ID
WRITEFILE(FileName, ID)

OUTPUT("Enter Description")
INPUT Description
WRITEFILE(FileName, Description)

OUTPUT("Enter Price")
INPUT Price
WRITEFILE(FileName, Price)

CLOSEFILE FileName

ENDPROCEDURE

NOTE: EACH DATA ITEM BECOMES STRING WHEN STORED IN A TEXT FILE.

Teacher : Shyam Subrahmanya 138 | P a g e


P2 Computer Science 9618

Q2.Use the file structure shown. (a) Write a procedure ReadNow( ) that takes FileName as a
parameter. It reads and outputs all the records from the text file. (b) Write a procedure AppendNow( )
that takes FileName as a parameter and inserts new record in the text file.

0198Onion34.50 Assume

0786Mango12.99 ID is 4 characters long

0124Apple12.50 Description is variable length

…. Price is 5 characters long

….

(a)PROCEDURE ReadNow(FileName :STRING )


DECLARE data:STRING
DECLARE ID: STRING
DECLARE Description: STRING
DECLARE Price: REAL
DECLARE StrPrice :STRING
DECLARE Pos :INTEGER

OPENFILE(FileName FOR READ)

WHILE NOT EOF(FileName)


READFILE (FileName, data)

ID  LEFT(data, 4)

Description  MID(data, 5, LENGTH(data)-9)

StrPriceRIGHT(data, 5)
Price STRING_TO_NUM (StrPrice)

OUTPUT (“ID IS ” & ID)


OUTPUT (“Desc is” & Description)
OUTPUT (“Price is ” & Price)

ENDWHILE
CLOSEFILE FileName

ENDPROCEDURE

0198 Onion 34.50


Apply
4 +x +5 LENGTH(data)=4+x+5 formula
x = LENGTH(data)-(4+5)

x = LENGTH(data) -9

Teacher : Shyam Subrahmanya 139 | P a g e


P2 Computer Science 9618

(b)PROCEDURE AppendNow(FileName :STRING )

DECLARE ID: STRING


DECLARE Description: STRING
DECLARE Price: REAL

OPENFILE(FileName FOR APPEND)

OUTPUT("Enter ID")
INPUT ID
WRITEFILE(FileName, ID)

OUTPUT("Enter Description")
INPUT Description
WRITEFILE(FileName, Description)

OUTPUT("Enter Price")
INPUT Price
WRITEFILE(FileName, Price)

CLOSEFILE FileName

ENDPROCEDURE

Teacher : Shyam Subrahmanya 140 | P a g e


P2 Computer Science 9618

Q1.Write a procedure TEST( ) that takes a string array MyArray as a parameter. It copies the first 5
elements of MyArray to a new file MyFile.txt.

Answer
PROCEDURE TEST(MyArray:Array OF STRING)
DECLARE Data : STRING
DECLARE count : INTEGER

OPENFILE(“MyFile.txt” FOR WRITE)

FOR count 1 to 5
WRITEFILE(“MyFile.txt”, MyArray[count])
ENDFOR

CLOSEFILE “MyFile.txt”

ENDPROCEDURE

Q2.Write a procedure FINAL( ) that takes a STRING array MyArray as a parameter. It copies the first 5
lines from MyFile.txt to Array MyArray.

Answer
PROCEDURE FINAL( MyArray: ARRAY OF STRING)
DECLARE count :INTEGER
OPENFILE(“MyFile.txt” FOR READ)

FOR count 1 to 5
READFILE (“MyFile.txt”, MyArray[count])
ENDFOR

CLOSEFILE “MyFile.txt”

ENDPROCEDURE

Practice question

Q5 (b) May/June 2016 9608 P21

9608/22/O/N/17 Homework

Teacher : Shyam Subrahmanya 141 | P a g e


P2 Computer Science 9618

Searching in a Text File Vs Searching in an Array


PROCEDURE search(FileName : STRING, item : STRING)

DECLARE Found : Boolean


DECLARE data : String

OPENFILE(FileName FOR READ)


Found  False

WHILE NOT EOF(FileName) And Found = False


READFILE (FileName, data)
If data = item
THEN
OUTPUT ("item has been found")
Found  True
ENDIF

ENDWHILE

IF Found = False
THEN
OUTPUT("Item is not in the file")
ENDIF

CLOSEFILE FileName

ENDPROCEDURE--------------------------------------------------------------

PROCEDURE searchInArray(MyArray:ARRAY OF STRING, item : String)

DECLARE Found : Boolean


DECLARE data : String
DECLARE Index : Integer

Found  False
Index  1
//Assume Array has upperbound 5

WHILE Index <= 5 And Found = False


data  MyArray(Index)
IF data = item
THEN
OUTPUT("item has been found at Index " & Index)
Found  True
ENDIF

Index = Index + 1
END WHILE

IF Found = False
THEN
OUTPUT("Item is not in the Array")
ENDIF
ENDPROCEDURE

Teacher : Shyam Subrahmanya 142 | P a g e


P2 Computer Science 9618

SUMMARY OF FORMATS

Input INPUT Marks

Output OUTPUT Marks

Comment //This is a comment

Built-in MOD(10,3)

functions
DIV( 10,3)

Result ← 2^3

Num ← INT (3.5)

Num ← 5/2

Otherwise as per the CAIE INSERT

Teacher : Shyam Subrahmanya 143 | P a g e


P2 Computer Science 9618

Iteration FOR X←1 TO 10

ENDFOR

WHILE COUNT<10

ENDWHILE

REPEAT

UNTIL count=10

Selection IF count>1

THEN

OUTPUT “TRUE”

ELSE

OUTPUT “FALSE”

ENDIF

Teacher : Shyam Subrahmanya 144 | P a g e


P2 Computer Science 9618

SELECTION

Pseudocode

CASE OF ______ CASE OF _________ CASE OF ____

‘A’: ____ “Apple”: _____ 1: ________

‘B’:____ “Banana”:____ 2:________

‘C’: ____ “Mango”: _____ 3: ________

OTHERWISE _____ OTHERWISE _____ OTHERWISE

ENDCASE ENDCASE ENDCASE

OTHERWISE IS OPTIONAL

String CHR(S)

Operations

ASC( S)

LENGTH(S)

LEFT(S, L)

RIGHT (S, L)

MID(S, P, L)

TO_UPPER( )

Teacher : Shyam Subrahmanya 145 | P a g e


P2 Computer Science 9618

TO_LOWER( )

UCASE( )

LCASE( )

Concatenation “Wi” & “Fi” //PREFERRABLE

“Wi” + “Fi”

Random Num←

Number RANDOMBETWEEN(MIN,MAX)

//INTEGER NUMBER

Num← RND( ) //REAL NUMBER BETWEEN 0-1

PROCEDURE ADD(Num1 : INTEGER)

……

ENDPROCEDURE

Procedure Call Call Add(2)

Call Add(x)

Teacher : Shyam Subrahmanya 146 | P a g e


P2 Computer Science 9618

FUNCTION ADD(NUM1 : INTEGER) RETURNS INTEGER

……

RETURN RESULT

ENDFUNCTION

//Note

RETURNS in the header

RETURN at the end

Function Call Answer←Add(4)

Answer←Add(num1)

OUTPUT(Add(4))

Num←Add(x) + 2

Teacher : Shyam Subrahmanya 147 | P a g e


P2 Computer Science 9618

Parameter Passing PROCEDURE Test(BYVALUE x)

PROCEDURE Test(BYREF y)

Declaration DECLARE Prices: ARRAY [1: 5] OF CURRENCY

1D Array DECLARE Num: ARRAY [0: 9] OF INTEGER

//Note

//It has LowerBound and UpperBound both

1D Array as a parameter PROCEDURE TEST(DETAIL:ARRAY OF String)

1D Array as an argument Call TEST(Detail)

2D Array DECLARE Data: ARRAY [1: 4, 1:3] OF INTEGER

Declaration //4 Rows and 3 columns

DECLARE Sale: ARRAY [0: 4, 0:3] OF INTEGER

//5 Rows and 4 columns

2D Array as a parameter PROCEDURE TEST(DETAILS:ARRAY OF STRING)

//Same as 1D

2D argument Call TEST(Details)

//Same as 1D

Teacher : Shyam Subrahmanya 148 | P a g e


P2 Computer Science 9618

File Operations

OPENFILE("TESTFILE.txt" FOR WRITE)

OPENFILE("TESTFILE.txt" FOR APPEND)

OPENFILE("TESTFILE.txt" FOR READ)

WRITEFILE(“TESTFILE.txt” , data)

READFILE (“TESTFILE.txt”, data)

EOF(“TESTFILE.TXT”)

CLOSEFILE(“TESTFILE.txt”)

Teacher : Shyam Subrahmanya 149 | P a g e

You might also like