AS Pseudocode Notes Paper2
AS Pseudocode Notes Paper2
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
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
Programming Basics
What is an Algorithm?
An algorithm is a series of instructions or steps for the solution of a problem.
Pseudocodes
(English statements)
Algorithm Converts to
(Program design)
Program flowchart
(graphical representation
of a solution)
Program code on
computer
Data types
Pseudocode
STRING
DATE
CHAR
BOOLEAN
INTEGER
CURRENCY
REAL
Note
Variable average is always Real data type because it involves a divide operation.
Pseudocode FORMATS
CONSTANT Pi=3.14
CONSTANT Tax=10
Count ← 0
Count ← Count+1
INPUT <identifier>
INPUT Marks
OUTPUT <string>
OUTPUT “Hello”
OUTPUT <identifier(s)>
OUTPUT Marks
// this is a comment
Built-in functions
//INT is a built in function, returns only integer part of the decimal number, Num is 3
Precedence
B Brackets
E Exponent
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
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
Variable ← Variable + 2
Example
Variable ← Variable + 3
Example
**Similarly students should be able to write statements to increment any step size.
Totaling
(step size is variable i.e. varying every time)
Example
Method 1
Method 2
Control Structures
There are 3 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
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
Pseudocode
THEN
On a new line
SEPARATE IF example
NESTED IF example
Pseudocode CASE
Pseudocode CASE
‘A’: Output “Excellent” 90 to 100: Output “Excellent” “Apple”: Output “Very Healthy”
“Documentary”: <50:
”Movies”: 50 to 80:
“Drama”: >80:
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
//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
OUTPUT “good”
ENDCASE
ELSE
NEXT
IF height > 6.5
THEN
OUTPUT “Very Tall”
ELSE
CASE STRUCTURE
Q1.
Pseudocode
INPUT Marks
CASE OF Marks
40 TO 60 :OUTPUT("Grade is C")
61 TO 80 :OUTPUT("Grade is B")
OTHERWISE OUTPUT(“Invalid
Entry”)
ENDCASE
Q2.
PSEUDODCODE
40 TO 49
ITERATION
Iteration
Pseudocode
Types of loops
For_Next loop
As long as the condition is false, it keeps looping. If the condition never becomes true, it will result
in an infinite loop.
As long as the condition is true, it keeps looping. If the condition never becomes false, it will result
in an infinite loop.
Example : Write pseudocode to input 5 numbers, find the total and output the sum.
INPUT number
OUTPUT total
ENDFOR count
Both are acceptable
ENDFOR
Teacher : Shyam Subrahmanya 36 | P a g e
P2 Computer Science 9618
-----------------------------------------
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
-----------------------------------------
max 0
min 100
mark 0
count count + 1
ENDWHILE
OUTPUT ("min is " & min)
OUTPUT("max is " & max)
Trace Table
Input values are 4, 3, 6, 9, 2, 1
//Method 2 - min and max can be initialized with the first input
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
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
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.
Q. Input Numbers until -1 has been entered. Output the minimum number.
Min100
INPUT Number
ENDWHILE
Note: While loop may not execute even once. Repeat loop will execute at least once.
b) Using REPEAT
DECLARE Min, Number : INTEGER
Min100
INPUT Number
REPEAT
INPUT Number
UNTIL NUMBER = -1
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
ENDWHILE
OUTPUT length
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
CASE OF code
ENDCASE
Input code
End while
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
ENDPROCEDURE
NOTE:
Nested IF
IF ….
IF…..
…………………..
END IF
END IF
VB code
Nested For
FOR ROW= 1 TO 5
FOR COL= 1 TO 8
…………………
NEXT COL
NEXT ROW
Nested Loop
Do
………………………….
END WHILE
Pseudocode
Note: It is compulsory to initialize counters, totals, min and max.
Examples
IF Num=0
Repeat
….
Until Found=True
Num←0
Found←True
Min←100
Max←Num
In pseudocodes
count←5 statement is correct
If count←5 condition is incorrect
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
String operations
EXAMPLE : SIGN UP ACCOUNTS
AliSarim
SarimA
Ali.S
Ali.Sa
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("School", 4,3)
TO_UPPER("temp")
TO_LOWER("CaMeL CaSe")
Concatenation
Joining two strings
& + operators are used for
concatenation
//Prefer using & instead of +
String operations
Page 260 text book
str1 "Pakistan"
OUTPUT(LEFT(str1, 3))
OUTPUT (RIGHT(str1, 4))
OUTPUT (MID(str1, 2, 5))
OUTPUT (TO_UPPER(str1))
OUTPUT (TO_LOWER(str1))
OUTPUT (CHR(65))
OUTPUT (CHR(68))
INPUT str1
str2 Left(str1, 3))
str2 TO_UPPER(str1)
str2 TO_LOWER(str1)
9608/21/M/J/16
Answer
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
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
CALL DISPLAY("876ACCTHina")
ThisString "hello"
Next
Output would be
ThisString "hello369"
counter 0
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.
Pseudocode_Strings
9608/21/M/J/17
CountU 0
CountL 0
CountD 0
Other 0
THEN
CountD CountD+1
ELSE
THEN
CountL CountL+1
ELSE
THEN
CountU CountU+1
ELSE
Other Other + 1
ENDIF
ENDIF
ENDIF
ENDFOR continued…
THEN
Result TRUE
ELSE
Result FALSE
ENDIF
RETURN Result
ENDFUNCTION
9608/22/M/J/17
Answer
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
ISNUM is a built-in function that returns TRUE if the argument is numeric otherwise returns FALSE.
Example
Str1 ”87534”
IF ISNUM(Str1)
THEN
ENDIF
NOTE:
Str2 “7@GF”
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
SPECIMEN INSERT P2
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.
RND( )
Num← RND( )
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]
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.
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.
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'
Procedure Vs Function
Page 262 ; 265
Procedure Function
1 PROCEDURE Add(num1 : Integer, num2 : 1 FUNCTION Add(num1 : Integer, num2 : Integer) RETURNS
Integer) Integer
3 Result←num1+num2 3 Result←num1+num2
6 END FUNCTION
NOTE
Line #1
Line # 5
ENDPROCEDURE
ENDFUNCTION
Subroutine Call
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:
Classwork
Write subroutine headers for the following
Instead of
RETURN ValueToReturn
FUNCTION Add(num1 : Integer, num2 : Integer) RETURNS FUNCTION Add(num1 : Integer, num2 : Integer) RETURNS
INTEGER INTEGER
Result←num1+num2 Result←num1+num2
Procedure
Pseudocode
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.
…….
ENDPROCEDURE
CALL Add(x,y)
NOTE
Errors
Data type of argument does not match with data type of parameters
Q5. The company wants a program to output the total monthly sales for one of the
selected websites.
The function returns the total number of bicycles sold for the given month and website.
The function will use the following:
… …
ENDPROCEDURE
CALL MyProc(45)
…..
ENDFUNCTION
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()
INPUT Num
OUTPUT Num*2
END PROCEDURE
2. Hardcode
PROCEDURE DOUBLE()
Num= 5
OUTPUT Num*2
END PROCEDURE
3. Global variable
//Some value has been set by other subroutines
PROCEDURE DOUBLE()
OUTPUT Num*2
END PROCEDURE
4. Parameter passing
//Procedure is receiving the value of Num as a parameter
OUTPUT Num*2
END PROCEDURE
PROCEDURE DOUBLE()
Num← STRING_To_NUM(Data)
OUTPUT Num*2
CLOSEFILE(“TEST.txt”)
END PROCEDURE
_________________________________________________________________________
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.
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.
DISADVANTAGE OF by reference:
Weak security because procedure can modify the caller’s data at will, possibly changing
that data.
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.
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.
BYVALUE
Consider the following program
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
BYREF
Consider the following program
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
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
SCOPE of a variable
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.
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
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
Arrays
1D Array page 212 text book
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 size: 5
Index: 1 to 5
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
Example : Write a pseudocode to input 5 prices. Find and output the average price.
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
Example : Write a pseudocode to input 5 prices using an array Prices. Find and output the
average price.
ENDFOR
Average←Total/5
For
While
Repeat
Pseudocode Syntax
Input Num[count]
ENDFOR
count←1
Repeat
Input Num[count]
count←count+1
Until count>1000
count←1
Input Num[count]
count←count+1
ENDWHILE
Output Num[7]
Marks [Index] ← -1 ( or 0)
CheckerBoard [Index] ← “ ”
Number[Index] ← 0
Product[Index] ← 1
1D Vs 2D Array
Pseudocode
1 D array is a list
Example 1 D array
//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
FOR count 1 To 5
OUTPUT Num[count]
ENDFOR
Index 1
Found False
Index Index + 1
ENDWHILE
IF Found = False
THEN
OUTPUT "Item is not in the list"
ENDIF
//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
PROCDEURE SEARCH( )
Index 1
Found False
Index Index + 1
ENDWHILE
IF Found = False
THEN
OUTPUT "Item is not in the list"
ENDIF
ENDPROCEDURE
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.
Index 1
Found False
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.
(c) Write the corresponding function call. Assign the value returned to a new variable result.
Assume 25 is the argument.
Homework
Modify the above PSEUDOCODE. Implement it as a menu driven program using VB.
PROCEDURE Menu( )
ENDPROCEDURE
To implement multiple search, modify the search subroutine using one of the following
If TO_LOWER(words(Index)) = TO_LOWER(item)
Practice Questions
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
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
PROCEDURE Search1( )
Index 1
Found False
Index Index + 1
ENDWHILE
IF Found = False
THEN
OUTPUT "Item is not in the list"
ENDIF
ENDPROCEDURE
PROCEDURE Search2( )
Index 1
Found False
REPEAT
Index Index + 1
IF Found = False
THEN
OUTPUT "Item is not in the list"
ENDIF
ENDPROCEDURE
PROCEDURE Search3( )
Found False
FOR Index 1 to 5
ENDFOR
IF Found = False
THEN
OUTPUT "Item is not in the list"
ENDIF
ENDPROCEDURE
Pseudocode Syntax
Subroutine Header
PROCEDURE MyProgram()
DECLARE Details[5] : String
//Call to a procedure/Subroutine
Call InitialiseArray(Details)
End PROCEDURE
Arguments
Practice questions
Q1.a) Write a subroutine MyMinimum( )
Main( )
Main( )
Bubble sort
Sorting
Concept of PASSES
1
2
3
4
5
6
7
ENDFOR
Note : Index 1 to 7
Total Number of elements 7
Because last element left is always sorted (there is no other element to compare it with).
PASSES
FOR Index 1 TO n
ENDFOR
ENDFOR
FOR Index 1 TO n
ENDIF
ENDFOR
ENDFOR
ENDFOR
In the loop :
Compare 5 pairs in pass 2
n Maxlndex – 1
FOR Index 1 TO n
ENDIF
ENDFOR
nn-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.
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.
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
nn-1
UNTIL NoMoreSwaps = TRUE
Practice
Homework
9608/22/O/N/16 Q6 & Q4
2D Array
[1] Name [2] Email [3] DOB [4] ID
[3]
2D Array
2D ARRAY
PROCEDURE TwoDArray()
//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
Found False
OUTPUT("Enter item to search")
INPUT Item
FOR Row 1 To 3
FOR Col 1 To 4
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
Call TEST(Details)
FOR Col 1 To 3
OUTPUT ProductionData [3, Col]
ENDFOR
ENDPROCDEURE
PROCEDURE INPUT()
FOR Row 1 To 4
OUTPUT “Enter data”
INPUT ProductionData [Row, 1]
ENDFOR
ENDPROCDEURE
PROCEDURE CELL()
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.
File handling
WRITE
Program File
READ
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.
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.
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.
Using 2 files
Read data from FileA
Convert the data into uppercase
Save the data in FileB
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.
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
CLOSEFILE(“TESTFILE.txt”)
PROCEDURE MENU( )
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( )
ENDCASE
ENDPROCEDURE
PROCEDURE ReadNow( )
CLOSEFILE FileName
ENDPROCEDURE
PROCEDURE AppendNow( )
OUTPUT("Enter data")
INPUT Data
WRITEFILE(FileName, data)
CLOSEFILE FileName
ENDPROCEDURE
PROCEDURE WriteNow( )
WRITEFILE(FileName , data)
CLOSEFILE FileName
ENDPROCEDURE
9608/21/O/N/17
ID 0198 indicates
string datatype
because of
leading zero
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.
ENDWHILE
CLOSEFILE FileName
ENDPROCEDURE
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.
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
….
ID LEFT(data, 4)
StrPriceRIGHT(data, 5)
Price STRING_TO_NUM (StrPrice)
ENDWHILE
CLOSEFILE FileName
ENDPROCEDURE
x = LENGTH(data) -9
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
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
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
9608/22/O/N/17 Homework
ENDWHILE
IF Found = False
THEN
OUTPUT("Item is not in the file")
ENDIF
CLOSEFILE FileName
ENDPROCEDURE--------------------------------------------------------------
Found False
Index 1
//Assume Array has upperbound 5
Index = Index + 1
END WHILE
IF Found = False
THEN
OUTPUT("Item is not in the Array")
ENDIF
ENDPROCEDURE
SUMMARY OF FORMATS
Built-in MOD(10,3)
functions
DIV( 10,3)
Result ← 2^3
Num ← 5/2
ENDFOR
WHILE COUNT<10
ENDWHILE
REPEAT
UNTIL count=10
Selection IF count>1
THEN
OUTPUT “TRUE”
ELSE
OUTPUT “FALSE”
ENDIF
SELECTION
Pseudocode
OTHERWISE IS OPTIONAL
String CHR(S)
Operations
ASC( S)
LENGTH(S)
LEFT(S, L)
RIGHT (S, L)
MID(S, P, L)
TO_UPPER( )
TO_LOWER( )
UCASE( )
LCASE( )
“Wi” + “Fi”
Random Num←
Number RANDOMBETWEEN(MIN,MAX)
//INTEGER NUMBER
……
ENDPROCEDURE
Call Add(x)
……
RETURN RESULT
ENDFUNCTION
//Note
Answer←Add(num1)
OUTPUT(Add(4))
Num←Add(x) + 2
PROCEDURE Test(BYREF y)
//Note
//Same as 1D
//Same as 1D
File Operations
WRITEFILE(“TESTFILE.txt” , data)
EOF(“TESTFILE.TXT”)
CLOSEFILE(“TESTFILE.txt”)