# CS - P2 Notes

```CS - P2 Notes by Mustafa Aamir
Standard methods of solution
Linear search
Here is a complete program that includes the LinearSearch function and
demonstrates how it can be used with test data:
FUNCTION LinearSearch(array : ARRAY OF INTEGER, number : INTEGER, length : INTEGER) RE
TURNS INTEGER
FOR i = 0 TO length - 1
IF array[i] = number THEN
RETURN i
ENDIF
ENDFOR
RETURN -1
ENDFUNCTION
// Test data
array = [5, 3, 8, 6, 1]
number = 6
length = 5
// Call the LinearSearch function with test data
result = LinearSearch(array, number, length)
// Output the result
OUTPUT &quot;Index of &quot;, number, &quot; in array: &quot;, result
This program defines the
LinearSearch
function as described earlier. It then defines
some test data: an array of 5 elements and a number to search for in the array. The
program calls the LinearSearch function with these values as arguments and stores
the result in a variable named result . Finally, the program outputs the result to show
the index of the number in the array .
When run, this program will output: Index of 6 in
of number (6) was found at index 3 in the array .
array: 3
, indicating that the value
Here is a modified version of the program that performs a linear search for the
substring “tion” in the string “Station ring was cancelled”:
CS - P2 Notes by Mustafa Aamir
1
FUNCTION LinearSearchString(string : STRING, substring : STRING) RETURNS INTEGER
length = LENGTH(string) - LENGTH(substring) + 1
FOR i = 0 TO length - 1
IF SUBSTRING(string, i, LENGTH(substring)) = substring THEN
RETURN i
ENDIF
ENDFOR
RETURN -1
ENDFUNCTION
// Test data
string = &quot;Station ring was cancelled&quot;
substring = &quot;tion&quot;
// Call the LinearSearchString function with test data
result = LinearSearchString(string, substring)
// Output the result
OUTPUT &quot;Index of '&quot;, substring, &quot;' in string: &quot;, result
This program defines a new function named LinearSearchString that takes two
parameters: string and substring . The function searches for the first occurrence
of substring in string using a linear search algorithm.
The function calculates the length of the search range as the difference between the
lengths of string and substring , plus 1. It then uses a for loop to iterate over this
range of indices in string . In each iteration, it extracts a substring of string starting
at index i and with the same length as substring , using the SUBSTRING function. It
then compares this extracted substring with substring . If they are equal, the function
returns the index i where substring was found.
In this example, we define a string and a substring to search for in the string. We
then call the LinearSearchString function with these values as arguments and store
the result in a variable named result . Finally, we output the result to show the index
of
substring
in
string
.
When run, this program will output:
value of
substring
Index of 'tion' in string: 2
(“tion”) was found at index 2 in the
string
, indicating that the
.
Bubble sort
Here’s an example of a pseudocode for the bubble sort algorithm that sorts an
array arr of n elements in ascending order:
bubble_sort(arr, n)
for i = 0 to n-2
for j = 0 to n-2-i
CS - P2 Notes by Mustafa Aamir
2
if arr[j] &gt; arr[j+1]
swap arr[j] and arr[j+1]
end if
end for
end for
This pseudocode defines a function named bubble_sort that takes two
parameters: arr and n . The function uses two nested for loops to iterate over the
elements of the array arr . In each iteration of the inner loop, it compares two
adjacent elements arr[j] and arr[j+1] . If the element on the left is greater than the
element on the right, the function swaps their positions. This process continues until
all elements are sorted in ascending order.
bubble_sort(arr, n)
repeat
swapped = false
for i = 1 to n-1
if arr[i-1] &gt; arr[i]
swap arr[i-1] and arr[i]
swapped = true
end if
end for
until not swapped
Total - Count - Min, Max, Avg
Here’s an example of a pseudocode that calculates the total, count, minimum,
maximum, and average of an array arr of n elements:
calculate_stats(arr, n)
total = 0
count = 0
min_value = arr[0]
max_value = arr[0]
for i = 0 to n-1
total = total + arr[i]
count = count + 1
if arr[i] &lt; min_value
min_value = arr[i]
end if
if arr[i] &gt; max_value
max_value = arr[i]
end if
end for
average = total / count
CS - P2 Notes by Mustafa Aamir
3
This pseudocode defines a function named calculate_stats that takes two
parameters: arr and n . The function initializes variables total , count , min_value ,
and max_value to their initial values. Then it uses a for loop to iterate over the
elements of the array arr . In each iteration, it updates the values
of total , count , min_value , and max_value based on the current element arr[i] .
After the loop finishes, the function calculates the average value by dividing the total
by the count. Finally, it returns all calculated values as the output of the function.
Procedure Swaps
// This procedure swaps
// values of X and Y
PROCEDURE SWAP(X : INTEGER, Y : INTEGER)
Temp ← X // temporarily store X
X ← Y
Y ← Temp
ENDPROCEDURE
This pseudocode defines a procedure named SWAP that takes two integer
parameters X and Y . The procedure swaps the values of X and Y by temporarily
storing the value of X in a variable named Temp , then assigning the value of Y to X ,
and finally assigning the value of Temp to Y . This means that after calling this
procedure with two variables as arguments, their values will be exchanged. For
example, if you call SWAP(A, B) where A is 3 and B is 4, after the procedure is
executed, the value of A will be 4 and the value of B will be 3.
Validation Checks
Range Check
OUTPUT &quot;Please enter the student's mark: &quot;
REPEAT
INPUT StudentMark
IF StudentMark &lt; 0 OR StudentMark &gt; 100
THEN
OUTPUT &quot;The student's mark should be in the the range of 0 to 100 inclus
.
ive, please re-enter the mark: &quot;
ENDIF
UNTIL StudentMark &gt;= 0 AND StudentMark &lt;= 100
CS - P2 Notes by Mustafa Aamir
4
Length Check:
REPEAT
THEN
OUTPUT &quot;This is not 8 characters. Enter again: &quot;
ENDIF
Type Check:
OUTPUT &quot;How many siblings do you have?: &quot;
REPEAT
INPUT Siblings
IF Siblings &lt;&gt; DIV(Siblings, 1)
THEN
OUTPUT &quot;Enter a whole number: &quot;
ENDIF
UNTIL Siblings = DIV(Siblings, 1)
Presence Check:
REPEAT
INPUT Name
IF Name = &quot;&quot; THEN
OUTPUT &quot;Enter something???: &quot;
ENDIF
UNTIL Name &lt;&gt; &quot;&quot;
Format Check:
format_check(value, format)
if value matches format
return true
else
return false
end if
CS - P2 Notes by Mustafa Aamir
5
This pseudocode defines a function named format_check that takes two
parameters: value and format . The function checks if the given value matches the
specified format . If it does, the function returns true , otherwise it returns false .
Check Digit:
check_digit(value : INTEGER) RETURNS BOOLEAN
sum = 0
FOR i = 0 to length_of(value)-2
digit = value[i]
weight = (i mod 2) + 1
sum = sum + (digit * weight)
NEXT i
check_digit = (10 - (sum mod 10)) mod 10
IF check_digit == value[length_of(value)-1]
RETURN True
ELSE
RETURN False
ENDIF
This pseudocode defines a function named check_digit that takes one
parameter: value . The function calculates a check digit using the Luhn algorithm and
compares it with the last digit of the given value . If they match, the function
Test Data
Explanation of normal, abnormal, extreme, and boundary test data with examples:
1. Normal test data: This type of test data represents typical inputs that a program
is expected to handle under normal operation. For example, if a program
calculates the square root of a number, normal test data would include positive
numbers like 4 or 9.
2. Abnormal test data: This type of test data represents inputs that are outside the
range of valid inputs that a program is expected to handle. For example, if a
program calculates the square root of a number, abnormal test data would
include negative numbers like -4 or -9.
3. Extreme test data: This type of test data represents inputs that are at the
extreme ends of the range of valid inputs that a program is expected to handle.
For example, if a program calculates the square root of a number and the valid
input range is between 0 and 100, extreme test data would include numbers like
0 or 100.
CS - P2 Notes by Mustafa Aamir
6
4. Boundary test data: This type of test data represents inputs that are at or near
the boundaries between valid and invalid inputs. For example, if a program
calculates the square root of a number and the valid input range is between 0
and 100, boundary test data would include numbers like -1 (just below the lower
boundary), 0 (at the lower boundary), 100 (at the upper boundary), and 101 (just
above the upper boundary).
Types of Loops
Pre-condition and post-condition loops are two types of loops that are used to repeat
a block of code a certain number of times or until a certain condition is met. The
main difference between them is when the loop condition is checked:
1. Pre-condition loop: In a pre-condition loop, the loop condition is checked before
each iteration of the loop. If the condition is true , the loop body is executed. If
the condition is false , the loop exits and the program continues with the next
statement after the loop. An example of a pre-condition loop is a while loop in
many programming languages.
2. Post-condition loop: In a post-condition loop, the loop condition is checked after
each iteration of the loop. This means that the loop body is always executed at
least once, even if the condition is false on the first check. If the condition is
true , the loop continues with the next iteration. If the condition is false , the loop
exits and the program continues with the next statement after the loop. An
example of a post-condition loop is a do-while loop in many programming
languages.
3. Count-controlled loop: A type of loop that repeats a specific number of times.
The number of iterations is determined by a counter variable that is initialized
before the loop starts and is incremented or decremented in each iteration of the
loop. The loop continues until the counter variable reaches a specified limit. An
example of a count-controlled loop is a for loop.
MOD &amp; DIV
and DIV are two arithmetic operators that are used to perform integer division
and calculate the remainder of a division operation.
MOD
1.
: The MOD operator calculates the remainder of a division operation. For
example, 7 MOD 3 would return 1 , because when 7 is divided by 3, the
remainder is 1.
MOD
CS - P2 Notes by Mustafa Aamir
7
2.
: The DIV operator performs integer division, which means that the result of
the division is an integer, and any fractional part is discarded. For example, 7 DIV
3 would return 2 , because when 7 is divided by 3, the result is 2 with a
remainder of 1.
DIV
String Operations
LENGTH(&quot;Happy Days&quot;) //will return 10
LCASE(ęWę) //will return ęwę
UCASE(&quot;Happy&quot;) //will return &quot;HAPPY&quot;
SUBSTRING(&quot;Happy Days&quot;, 1, 5) //will return &quot;Happy&quot;
It is important to note that a space counts as a character.
SUBSTRING(&quot;Happy Days&quot;, 7, 4) //will return &quot;Days&quot;
ROUND( ) function
This pseudocode describes a function named ROUND that takes two parameters: an
identifier and a number of decimal places. The function returns the value of the
identifier rounded to the specified number of decimal places. The identifier should be
a real number (i.e., a number with a decimal point), and the number of decimal
places should be an integer.
For example, if you call ROUND(3.14159, 2) , the function will return the value 3.14 ,
because it rounds the value of the first parameter (3.14159) to 2 decimal places.
Similarly, if you call ROUND(3.14159, 3) , the function will return 3.142 , because it
rounds the value to 3 decimal places.
If you specify 0 as the number of decimal places in the ROUND function, it will round
the value of the identifier to the nearest whole number. For example, if you
call ROUND(3.14159, 0) , the function will return 3 , because it rounds the value of the
first parameter (3.14159) to 0 decimal places, which means rounding to the nearest
whole number. Similarly, if you call ROUND(3.5, 0) , the function will return 4 , because
it rounds up to the nearest whole number.
RANDOM( )
Returns a random number between 0 and 1 inclusive.
CS - P2 Notes by Mustafa Aamir
8
Value ← ROUND (RANDOM() * 6, 0) // returns a whole number between 0 and 6
In this example, the function RANDOM( ) generates values such as 0.2321 , 0.923 ,
0.192 which are REAL numbers between 1 and 0. If we tweak this program to
something like this:
FOR i = 1 to 10
Value ← ROUND (RANDOM() * 6, 0) // returns a whole number between 0 and 6
OUTPUT Value
NEXT i
This pseudocode uses a FOR loop to generate 10 random whole numbers between 0
and 6. In each iteration of the loop, the RANDOM() function is called to generate a
random decimal number between 0 and 1. This value is then multiplied by 6 to scale
it to the desired range of values. The ROUND() function is then called with two
arguments: the result of the multiplication and 0. The second argument specifies that
the result should be rounded to 0 decimal places, which means rounding to the
nearest whole number. The final result is a random integer between 0 and 6, which
is assigned to the variable Value and then output using the OUTPUT statement.
Here are ten possible outputs from running this pseudocode:
1
,
3
,
2
,
1
,
4
,
5
,
6
,
1
,
5
,
2
Procedure and Function
A procedure and a function are both subroutines that can be called from the main
program or from other subroutines to perform a specific task. The main difference
between them is that a function returns a value, while a procedure does not.
A procedure is a block of code that performs a specific task and can be called by
other parts of the program. It may take input parameters and may perform actions
that have side effects, such as modifying variables or printing output. However, it
does not return a value to the caller.
A function is similar to a procedure in that it is also a block of code that performs a
specific task and can be called by other parts of the program. However, unlike a
procedure, a function returns a value to the caller. This value is usually the result of
some calculation or operation performed by the function.
Here’s an example that shows the difference between a procedure and a function in
pseudocode:
CS - P2 Notes by Mustafa Aamir
9
PROCEDURE printSum(a, b)
sum = a + b
PRINT sum
ENDPROCEDURE
FUNCTION getSum(a, b)
sum = a + b
RETURN sum
END FUNCTION
x = 3
y = 4
printSum(x, y) // prints 7
z getSum(x, y) // z is assigned the value 7
In this example,
printSum
is a procedure that takes two input parameters
a
and
b
,
calculates their sum, and prints it. getSum is a function that also takes two input
parameters a and b , calculates their sum, but instead of printing it, it returns the
result to the caller.
When a function “returns a value”, it means that the function produces a result that is
passed back to the part of the program that called the function. This result can then
be used by the calling program as an input to another operation or as the value of a
variable.
In pseudocode, the return statement is used to specify the value that a function
returns. When a return statement is executed, the function immediately terminates
and control is returned to the calling program, along with the value specified in
the return statement.
Here’s an example that shows how a function can return a value in pseudocode:
FUNCTION square(x : INTEGER) RETURNS INTEGER
return x * x
ENDFUNCTION
y = 3
z = square(y) // z is assigned the value 9
In this example, square is a function that takes one input parameter x and returns
the result of multiplying x by itself. When the function is called with an argument
of 3 , it calculates 3 * 3 and returns the result 9 to the calling program. The calling
program then assigns this value to the variable z .
CS - P2 Notes by Mustafa Aamir
10
//Format according to the syllabus for Procedures.
PROCEDURE DefaultLine
CALL LINE(60)
ENDPROCEDURE
PROCEDURE Line(Size : INTEGER)
DECLARE Length : INTEGER
FOR Length ← 1 TO Size
OUTPUT '-'
NEXT Length
ENDPROCEDURE
IF MySize = Default
THEN
CALL DefaultLine
ELSE
CALL Line(MySize)
ENDIF
Defining and Calling Functions
FUNCTION SumSquare(Number1 : INTEGER, Number2 : INTEGER) RETURNS INTEGER
RETURN Number1 * Number1 + Number2 * Number2
ENDFUNCTION
OUTPUT &quot;Sum of squares = &quot;, SumSquare(10, 20)
Functions
function.
RETURN
values, therefore it is important to mention it when defining a
FUNCTION &lt;identifier&gt; RETURNS &lt;data type&gt;
&lt;statements&gt;
ENDFUNCTION
This is a function definition in a programming language. A function is a block of code
that performs a specific task and can be called by other parts of the program.
The &lt;identifier&gt; is the name of the function. The RETURNS &lt;data type&gt; specifies the
type of data that the function returns as output. The &lt;statements&gt; are the lines of
code that define what the function does. The ENDFUNCTION marks the end of the
function definition.
1D &amp; 2D Arrays
CS - P2 Notes by Mustafa Aamir
11
An array is a data structure that stores a collection of elements, where each element
can be accessed by its index. Arrays can have one or more dimensions, depending
on the number of indices needed to access their elements.
1. 1D arrays: A 1D array, also known as a one-dimensional array or a linear array,
is an array where each element is accessed by a single index. For example, you
could use a 1D array to store a list of numbers or a list of names. Here's an
example of how you could declare and initialize a 1D array in pseudocode:
numbers = [5, 3, 8, 6, 1]
In this example, numbers is a 1D array that stores 5 elements. The first element
has an index of 0 , the second element 3 has an index of 1 , and so on.
5
1. 2D arrays: A 2D array, also known as a two-dimensional array or a matrix, is an
array where each element is accessed by two indices. For example, you could
use a 2D array to store a table of data or a grid of values. Here's an example of
how you could declare and initialize a 2D array in pseudocode:
grid = [[1, 2], [3, 4], [5, 6]]
In this example, grid is a 2D array that stores 3 rows and 2 columns of elements.
The first row [1, 2] has an index of 0 , the second row [3, 4] has an index of 1 ,
and so on. Within each row, the first element 1 has an index of 0 , the second
element 2 has an index of 1 , and so on.
Nested iteration: To access all the elements in a multi-dimensional array such as a
2D array, you can use nested loops. For example, here's how you could use nested
loops to iterate over all the elements in the grid array from the previous example:
for i = 0 to grid.length - 1
for j = 0 to grid[i].length - 1
print grid[i][j]
end for
end for
In this example, the outer loop iterates over each row in the grid array using the
variable i , while the inner loop iterates over each element within the current row
using the variable
[j]
j
. In each iteration of the inner loop, the current element
grid[i]
is printed.
CS - P2 Notes by Mustafa Aamir
12
File Handling
// 1. Open a file for reading
OPENFILE &quot;input.txt&quot; FOR READ AS inputFile
// Read data from the file
// Close the input file
CLOSEFILE inputFile
// Process the data
data = data + 1
// Open a file for writing
OPENFILE &quot;output.txt&quot; FOR WRITE AS outputFile
// Write data to the file
WRITEFILE outputFile, data
// Close the output file
CLOSEFILE outputFile
In this example, we first open a file named “input.txt” for reading using
the OPENFILE command. The first argument is the name of the file and the second
argument specifies the mode in which the file is opened ( READ in this case).
The AS keyword is used to assign a name ( inputFile ) to the opened file for use in
subsequent operations.
Next, we read data from the file using the READFILE command. The first argument is
the name of the opened file ( inputFile ) and the second argument is the variable
( data ) that will store the data read from the file.
After reading the data, we close the input file using the
argument is the name of the opened file ( inputFile ).
CLOSEFILE
command. The
We then process the data by incrementing its value by 1.
Next, we open a file named “output.txt” for writing using the
OPENFILE
command. This
time, we specify WRITE as the mode in which to open the file. We also assign a name
( outputFile ) to the opened file for use in subsequent operations.
We then write data to the output file using the WRITEFILE command. The first
argument is the name of the opened file ( outputFile ) and the second argument is the
variable ( data ) containing the data to be written to the file.
Finally, we close the output file using the
CLOSEFILE
command.
Here is another example from the CS 2210 2023 Syllabus:
CS - P2 Notes by Mustafa Aamir
13
//This example uses the operations together, to copy a line of text from FileA.txt
//to FileB.txt
DECLARE LineOfText : STRING