0% found this document useful (0 votes)
25 views7 pages

Library Routines in Programming

Uploaded by

ahsan.arisha08
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)
25 views7 pages

Library Routines in Programming

Uploaded by

ahsan.arisha08
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

Computer Science

Teacher: Maruf Ahmed


Library routines, String manipulation, File handling

Program libraries / Library routines:


- A library routine is a debugged block of code, often designed to handle commonly occurring
problems or tasks.
- Library routines are stored in a program library and given names. This allows them to be called into
immediate use when needed, even from other programs.
- They are designed to be used frequently.

Some features of program libraries / library routines:


• Set of pre-written / pre-compiled / pre-tested subroutines
• can be linked into a program without amendment
• To perform common / complex tasks
• The program library can be referenced/imported
• The functions/routines can be called in one’s own program

Benefits of using library routines in a program:


• Code does not have to be written/re-written from scratch
• Code is already tested so it is more robust/likely to work/ should be relatively free from errors
• Precompiled
• Saves programming time
• The programmer can use e.g., mathematical functions that s/he may not know how to code
• If there is an improvement in the library routine the program updates automatically

Drawbacks of using library routines:


• Compatibility issue: May not work with the other code/may require changing program for it to work
• Not guaranteed thorough testing
• May be unknown or unexpected bugs / virus
• Library routine may not meet exact needs
• If library routine is changed there may be unexpected results / errors

You can only use the following four library routines in your pseudocode programs for mathematical
operation:
MOD( ) – Is used to perform integer division when one number is divided by another number and finds the
remainder. For example, MOD(7, 2) = 1
DIV( ) – Is used to perform integer division when one number is divided by another number and only the
whole number part of the answer (quotient) is retained. For example, DIV(9,4) = 2
ROUND( ) – Is used to return a value rounded to a specified number of digits / decimal places. The result
will either be rounded to the next highest or the next lowest value depending on whether the value of the
preceding digit is >=5 or <5. Example of ROUND for example, ROUND(4.56, 1) = 4.6
RANDOM( ) – Is used to generate random / pseudo random numbers within a specified range.
For example, RANDOM() * 10 returns a random number between 0 and 10 inclusive

Page 1 of 7
N.B. Every library routine has a parenthesis ( ) after the end of the name of the identifier and must contain
the exact number of parameters that needs to be passed for each routine and must be of the same data type as
per the definition of the library routine.

Here are some examples of the use of these library routines in pseudocode:
Value1 ← MOD(10, 3)
Returns the integer remainder after the division of 10 by 3 and the result 1 will be assigned to Value1. Data
type of Value1 must be integer.
Value2 ← DIV(10, 3)
Returns the integer quotient after the division of 10 by 3 and the result 3 will be assigned to Value2. Data
type of Value2 must be integer.
Value3 ← ROUND(6.97654, 2)
Returns the value rounded to 2 decimal places and the result 6.98 will be assigned to Value3. Data type of
Value3 must be real.
Value4 ← RANDOM()
By default, RANDOM() returns a random number between 0 and 1 inclusive in decimal form. It does not
receive any parameter which means by using the RANDOM() library routine it will always give a value
from 0 to 1 in decimal form automatically. For example, 0.12, 0.85, 0.001, 0.02 etc. The decimal point is
always preceded by 0.

N.B. MOD and DIV may also be used as operators in pseudocode.

Problem: Using library routine RANDOM(), generate 20 whole numbers in the range from 0 to 50. Display
each generated number. Write down the required pseudocode.

DECLARE Count : INTEGER


DECLARE Rnd, WholeRnd : REAL
FOR Count ← 1 TO 20
Rnd ← RANDOM() * 50 //This will multiply each generated random number by 50
WholeRnd ← ROUND(Rnd, 0) //This will round each generated number to nearest integer to 0 decimal
//place
//The above two statements can be written as one statement like
//WholeRnd ← ROUND(RANDOM() * 50, 0)
OUTPUT WholeRnd
NEXT Count

N.B. If the range of random values starts from 0 then multiply the RANDOM() function with the end of the
range value and use round function to 0 decimal place to be regarded as a whole number. In this case
multiply the RANDOM() function by 50.

Problem: Using library routine RANDOM(), generate 10 whole numbers in the range from 10 to 40.
Display each generated number. Write down the required pseudocode.

DECLARE Count : INTEGER


DECLARE Rnd, WholeRnd : REAL
FOR Count ← 1 TO 10
Rnd ← RANDOM() * 30 //This will multiply each generated random number by 30

Page 2 of 7
WholeRnd ← ROUND(Rnd, 0) + 10 //This will round each generated number to nearest integer to 0
//decimal place and add each value by 10
//The above two statements can be written as one statement like
//WholeRnd ← ROUND(RANDOM() * 30, 0) + 10
OUTPUT WholeRnd
NEXT Count

Process to generate a range of whole numbers that do not start from zero:
• Generate a random value with RANDOM() function first.
• Then multiply the value with a whole number. This whole number would be obtained by subtracting
the start value of the range from the end value of the range.
• Then add the start value of the range with the generated random number.
• ROUND() function needs to be used to make it 0 decimal place to be regarded as an integer.

String / Character manipulation


Strings are used to store text. Every string contains a number of characters, from an empty string, which has
no characters stored, to a maximum number specified by the programming language. The characters in a
string can be labeled by position number. The first character position in a string can start from 1 (one) or 0
(zero). But in pseudocode, the first position starts from 1 unless otherwise mentioned in the question
paper and in programming language it starts from 0. In all the following examples, we will assume the
string position starts from 1 in pseudocode.

The following string manipulation library routines are included in your syllabus:
- LENGTH()
- UCASE()
- LCASE()
- SUBSTRING()

LENGTH( ) – Takes STRING as a parameter and returns the number of characters in the string. For
example, the length of the string “Computer Science” is 16 characters. Remember that each space is also
counted as a character. The return value of LENGTH function is integer.
X ← LENGTH(“Computer Science”)
16 will be assigned to X
X ← LENGTH(MyString)
Whatever the number of characters in variable, MyString will be assigned to X.

UCASE( ) – Takes STRING as a parameter and returns the STRING in uppercase. For example, the string
“Computer Science” would become “COMPUTER SCIENCE”. The return value of UCASE function is
STRING. Anything other than letters in the string will remain as it is.
X ← UCASE(“Computer Science”)
Every character will be converted into capital letters so “COMPUTER SCIENCE” would be assigned to X
X ← UCASE(MyString)
Whatever is stored in variable, MyString will be converted into capital letters and then assigned to X

LCASE( ) – Takes STRING as a parameter and returns the STRING in lowercase. For example, the string
“Computer Science” would become “computer science”. The return value of LCASE function is
STRING. Anything other than letters in the string will remain as it is.
Page 3 of 7
X ← LCASE(“Computer Science”)
Every character will be converted into small letters so “computer science” would be assigned to X
X ← LCASE(MyString)
Whatever is stored in variable, MyString will be converted into small letters and then assigned to X

SUBSTRING( ) – It returns the extracted string from a given string. It requires 3 parameters to work with.
First parameter is a STRING, second and third parameters are integers. The first parameter indicates the
string on which the extraction will take place. The second parameter indicates the start position to extract
from and the third parameter is used to give the number of characters (quantity) to be extracted from the
given position. Both the second and third parameters are inclusive of the value. For example, the substring
“Science” could be extracted from “Computer Science”. The return value of SUBSTRING function is
STRING.
X ← SUBSTRING(“Computer Science”, 10, 7)
“Science” will be assigned to X
X ← SUBSTRING(MyString, 5, 4)
Whatever is stored in variable, MyString, the extraction will start from the 5th character and 4 characters
from that position will be assigned to the variable X

Pseudocode Example of a string manipulation problem:


(a) Write pseudocode example to declare variables P and Q, store “Hello World” in P and ‘w’ in Q.
(b) Write a pseudocode algorithm to:
- Convert P to lower case
- Find the position of Q in the string P (the first character in this string is in position 1)
- Store the position of Q in the variable Position

(a)
DECALRE P : STRING
P ← “Hello World”
DECLARE Q : CHAR
Q ← ‘w’

(b)
Solution with WHILE loop
P ← LCASE(P)
Counter ← 1
Position ← 0
WHILE Position = 0 AND Counter <= LENGTH(P) DO
ThisChar ← SUBSTRING(P, Counter, 1)
IF ThisChar = Q
THEN
Position ← Counter
ELSE
Counter ← Counter + 1
ENDIF
ENDWHILE

Page 4 of 7
Solution with REPEAT loop
P ← LCASE(P)
Counter ← 1
Position ← 0
REPEAT
IF SUBSTRING(P, Counter, 1) = Q
THEN
Position ← Counter
ELSE
Counter ← Counter + 1
ENDIF
UNTIL Position < > 0 OR Counter > LENGTH(P)

Solution with FOR loop //Not efficient as it will go till the end of the string
P ← LCASE(P)
Position ← 0
FOR Counter ← 1 TO LENGTH(P)
ThisChar ← SUBSTRING(P, Counter, 1)
IF ThisChar = Q
THEN
Position ← Counter
ENDIF
NEXT Counter

File handling
Computer programs store data in a file that will be required again later. While data is stored in RAM will be
lost when the computer is switched off, when data is saved to a file it is stored permanently.
Purpose of storing data in a file:
- Data stored in a file gives a permanent copy / prevents the data from being lost
- Data stored in a file can be accessed by the same program at a later date or accessed by another
program.
- Data stored in a file can also be sent to be used on other computer(s).
- Data can also be used as archive or backup.

According to your syllabus the file handling operation should be able to perform the following:
• Open, close and use a file for reading and writing
• read and write single items of data
• read and write a line of text

File Modes: refers to the purpose to open a file


The following file modes are used:

READ mode:
- is used to retrieve data / get data from an existing file
You must remember that an error will be generated by the operating system if a file does not exist and the
programmer is trying to open the file in READ mode.
Page 5 of 7
WRITE mode:
- is used to send data / transfer data to a file.
You must remember that WRITE mode will create a new file every time from scratch and any existing data
in the file will be overwritten.

N.B. This is to be remembered that reading data from a file is known as INPUT because the file sends data
to a computer system and the computer system receives the data as input. Whereas writing data into a file is
known as OUTPUT because the computer system sends data to a file and the file receives the data as output.
N.B. A file should be opened in only one mode at a time.

These are the pseudocode commands to be used to work with files


- OPENFILE
- READFILE
- WRITEFILE
- CLOSEFILE

The syntax to use the above commands:


The file needs to be opened before use, stating the mode of operation, before reading from or writing to it.
The syntax is as follows:
OPENFILE <File identifier> FOR <File mode>

The file identifier will be the name of the file with data type string. This will always be text files with .txt
extension.

Data is read from the file (after the file has been opened in READ mode) using the READFILE command as
follows:
READFILE <File Identifier>, <Variable>
When the command is executed, the data item is read and assigned to the variable.
Data is written into the file after the file has been opened using the WRITEFILE command as follows:
WRITEFILE <File identifier>, <Variable>
When the command is executed, the data is written into the file.
Every file must be closed when they are no longer needed using the CLOSEFILE command as follows:
CLOSEFILE <File identifier>

File handling operations:


Every file is identified by its filename. In this section, we are going to look at how to read and write a line of
text or a single item of data to a file. In your syllabus, only a line of text (not multiple lines) will be used to
read from a file or write into a file.

Here are pseudocode examples of writing a line of text to a file and reading the line of text back from the
file. The pseudocode algorithm has comments to explain each stage of the task.

Page 6 of 7
DECLARE TextLine : STRING
N.B. Any constant declared to hold a file name must be of STRING
CONSTANT MyFile ← [Link] //[Link] file has been assigned to constant MyFile
OPENFILE MyFile FOR WRITE // opens file in WRITE mode
The above line could have been written in the following way also by avoiding CONSTANT:
OPENFILE [Link] FOR WRITE // opens file in WRITE mode
OUTPUT "Please enter a line of text"
INPUT TextLine
WRITEFILE MyFile, TextLine //Whatever has been given as input in the variable TextLine, will be
// passed to the file "[Link]" and the data will be stored there
CLOSEFILE MyFile // closes the file

// reading a line of text from a file


DECLARE TextLine : STRING
OPENFILE [Link] FOR READ // opens file in READ mode
READFILE [Link], TextLine // reads a line of text from the file in TextLine
OUTPUT "The file contains this line of text:", TextLine //Displays the line of text on the screen
CLOSEFILE [Link] //closes the file

Example – File handling operations using two different modes together


This example uses the READ and WRITE operations together, to copy a line of text from [Link] to
[Link]
DECLARE LineOfText : STRING
OPENFILE [Link] FOR READ
OPENFILE [Link] FOR WRITE
READFILE [Link], LineOfText
WRITEFILE [Link], LineOfText
CLOSEFILE [Link]
CLOSEFILE [Link]

Page 7 of 7

Common questions

Powered by AI

File handling operations ensure data permanence by storing data in files, preventing loss after the computer is turned off. This allows data access across different programs or as a backup . The key operations include OPENFILE, READFILE, WRITEFILE, and CLOSEFILE. To read a line of text, the file is opened in READ mode, data is retrieved using READFILE, and then the file is closed. Writing involves opening the file in WRITE mode, transferring data via WRITEFILE, and closing the file afterward. An example includes reading text from 'MyText.txt' into 'TextLine' then displaying it . Writing involves capturing text input and writing it to 'MyText.txt' .

String manipulation involves changing the characters in strings using given library routines. Common routines include LENGTH(), UCASE(), LCASE(), and SUBSTRING(). LENGTH() returns the total number of characters including spaces; for example, the length of 'Computer Science' is 16 . UCASE() transforms all characters to uppercase, turning 'Computer Science' into 'COMPUTER SCIENCE' . LCASE() performs a similar change to lowercase, converting 'Computer Science' to 'computer science' . SUBSTRING() extracts a part of the string based on specified start and length positions, such as extracting 'Science' from 'Computer Science' by starting at position 10 and extracting 7 characters .

The RANDOM() function inherently generates a floating-point number between 0 and 1 . To generate whole numbers within a specific range, the output of RANDOM() must be multiplied by the range's size. For example, to generate numbers from 0 to 50, the RANDOM() value is multiplied by 50 and then rounded to the nearest integer using ROUND() to get whole numbers . If the range does not start at zero, the difference between the start and end values is used to scale RANDOM(), followed by rounding and then adding the starting value of the range .

Library routines provide numerous benefits, including the reuse of pre-written, pre-tested code, which saves programming time and ensures robust code likely to be relatively free of errors. They are also precompiled, and offer functionalities like mathematical operations which might be outside the coder's expertise . However, the drawbacks include potential compatibility issues with existing code, unknown bugs, or viruses not addressed by thorough testing. Additionally, a library routine might not meet the specific needs of a program, and changes to the routine could produce unexpected results . The decision to use library routines thus involves weighing their robust, tested, and efficient nature against potential incompatibility and specificity challenges.

Pseudocode representations of strings assume the position starts at 1, which can simplify string element access by aligning with human counting conventions as opposed to a zero-based index, as in many programming languages . This choice might reduce off-by-one errors typical in zero-based systems. The inclusion of library routines like LENGTH(), UCASE(), LCASE(), and SUBSTRING() offers clear syntax for common operations, reducing manual code complexity . However, using different starting indices could pose migration challenges when transitioning from pseudocode to language-specific syntax. This might generate compatibility difficulties and increase learning curves due to these syntactic differences.

To find the position of 'w' in 'Hello World', convert the string to lowercase with LCASE() for accurate character comparisons. Initialize a counter to traverse the string and a position variable to track 'w' . Using a WHILE loop, iterate, comparing each character (via SUBSTRING()). If 'w' is found, set position; otherwise increment counter until end . A REPEAT loop checks each character and exits once 'w' is found or the string ends, potentially more readable with a straightforward stop condition . A FOR loop can traverse set length ranges but isn't efficient, as it may unnecessarily check all positions despite finding 'w' .

File modes significantly impact operations. Opening a non-existent file in READ mode will generate an operating system error due to the absence of retrievable data . Using WRITE mode creates or overwrites a file completely, ensuring new data is stored, but risks data loss if misapplied . Importantly, files should be opened in only one mode at a time, as multiple modes could lead to data collisions and unintended overwrites. This single-mode operation guarantees better data integrity and less complexity during file handling .

The DIV() and MOD() functions facilitate integer division operations in pseudocode. DIV() provides the integer quotient of a division, discarding any remainder. When used with integers 10 and 3, DIV(10, 3) results in the quotient 3 . Conversely, MOD() offers the remainder of the division of two integers. For the same values, MOD(10, 3) results in a remainder 1 . These functions help achieve accurate and concise arithmetic calculations without floating points in pseudocode.

A robust pseudocode algorithm involves opening the source file in READ mode and the destination file in WRITE mode. Begin by reading the source file line-by-line using READFILE, checking if it contains data . Write to the destination immediately after each read using WRITEFILE to prevent redundancy. After transferring each line, close both files using CLOSEFILE commands to secure data integrity and avoid resource leaks . Implement checks for file existence and readability to preempt errors caused by opening non-existent files or improperly formatted lines.

To determine if two strings are anagrams, use UCASE() or LCASE() to unify the case format for each string ensuring comparisons aren't affected by capitalization. Next, extract and sort characters using a customized routine that could employ the SUBSTRING() function to organize each string's characters in a consistent order. Finally, compare the rearranged strings directly for equality. This method leverages pseudocode's standardized string comparison capabilities after ensuring uniform case and order, thus confirming the anagram status effectively without extraneous logic loops.

You might also like