Programming Notes for Mid-Year 2020 Computer Science 9618 Huma Imad 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 : Huma Imad 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 : Huma Imad 2|P a ge P2 Computer Science 9618 Teacher : Huma Imad 3|P a ge P2 Computer Science 9618 Teacher : Huma Imad 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) Converts to Algorithm (Program design) Program flowchart (graphical representation of a solution) Program code on computer Teacher : Huma Imad 5|P a ge P2 Computer Science 9618 Teacher : Huma Imad 6|P a ge P2 Computer Science 9618 Teacher : Huma Imad 7|P a ge P2 Computer Science 9618 Teacher : Huma Imad 8|P a ge P2 Computer Science 9618 Teacher : Huma Imad 9|P a ge P2 Computer Science 9618 Teacher : Huma Imad 10 | P a g e P2 Computer Science 9618 Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 Total← Total - ((20/100)*Total) …deduct 2 from a variable …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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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). Pseudocode Selection –IF Teacher : Huma Imad 19 | P a g e P2 Computer Science 9618 Pseudocode Selection- Case Teacher : Huma Imad 20 | P a g e P2 Computer Science 9618 Pseudocode THEN On a new line SEPARATE IF example Teacher : Huma Imad 21 | P a g e P2 Computer Science 9618 NESTED IF example Teacher : Huma Imad 22 | P a g e P2 Computer Science 9618 Teacher : Huma Imad 23 | P a g e P2 Computer Science 9618 Pseudocode CASE Teacher : Huma Imad 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 entry” OTHERWISE output ”invalid entry” OTHERWISE output ”invalid 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 : Huma Imad 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 : Huma Imad 26 | P a g e P2 Computer Science 9618 //include declarations count ←0 countA←0 Answer: //include declarations CountB←0 CountC←0 count ←0 WHILE count<8 countA←0 INPUT grade CountB←0 Count←count+1 CountC←0 IF grade=’A’ WHILE count<8 INPUT grade THEN OUTPUT “Excellent” Count←count+1 countA←countA+1 CASE of grade ‘A’: Output “Excellent” countA←countA+1 ‘B’: Output “good” ELSE If grade=’B’ THEN OUTPUT “good” countB←countB+1 ‘C’: countB←countB+1 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 Teacher : Huma Imad ENDWHILE 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 1.0 to 3.9: Output “short” 4.0 to 6.5: Output “good” > 6.5: Output “Very Tall” OTHERWISE output ”invalid entry” THEN OUTPUT “short” ELSE IF height>=4.0 AND height <= 6.5 THEN OUTPUT “good” ENDCASE NEXT ELSE IF height > 6.5 THEN OUTPUT “Very Tall” ELSE OUTPUT ”invalid entry” END IF END IF END IF ENDFOR Teacher : Huma Imad 28 | P a g e P2 Computer Science 9618 CASE STRUCTURE Q1. Pseudocode DECLARE Marks : Integer INPUT Marks CASE OF Marks < 40 :OUTPUT("Grade 40 TO 60 61 TO is U") :OUTPUT("Grade is C") 80 :OUTPUT("Grade is B") 81 TO 100 :OUTPUT("Grade is A") OTHERWISE OUTPUT(“Invalid Entry”) ENDCASE Teacher : Huma Imad 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 : Huma Imad 30 | P a g e P2 Computer Science 9618 Flowchart CASE STRUCTURE ITERATION Teacher : Huma Imad 31 | P a g e P2 Computer Science 9618 Teacher : Huma Imad 32 | P a g e P2 Computer Science 9618 Pseudocode Iteration Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 total ← total + number total ← total + number Count←count+1 FOR count ←1 TO 5 INPUT number ENDWHILE UNTIL count = 5 OUTPUT total OUTPUT total total ← total + number ENDFOR count OUTPUT total ENDFOR count Both are acceptable ENDFOR Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 Min100 INPUT Number WHILE Number < > -1 IF Number < Min THEN Min Number ENDIF One input before WHILE and one input before ENDWHILE so that rouge value is not processed. 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 Min100 INPUT Number REPEAT IF Number < Min THEN Min Number ENDIF INPUT Number UNTIL NUMBER = -1 OUTPUT ( “Min is ” & Min) Teacher : Huma Imad 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 < > ‘@’ length ← length +1 Input char has to be placed at the bottom of the loop INPUT char ENDWHILE OUTPUT length Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 If count←5 incorrect = is known as a relational operator ← 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 : Huma Imad 48 | P a g e P2 Computer Science 9618 ASCII Character Codes (0 through 127) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 N/A N/A N/A N/A N/A N/A N/A N/A (backspace) (tab) (line feed) N/A N/A (carriage return) N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A Teacher : Huma Imad 32 33 34 35 36 37 38 39 40 41 42 43 44 45 [space] ! " # $ % & ' ( ) * + , - 64 65 66 67 68 69 70 71 72 73 74 75 76 77 @ A B C D E F G H I J K L M 96 97 98 99 100 101 102 103 104 105 106 107 108 109 ` a b c d e f g h i j k l m 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 N O P Q R S T U V W X Y Z [ \ ] ^ _ 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 n o p q r s t u v w x y z { | } ~ N/A 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 : Huma Imad 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 : Huma Imad 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 OUTPUT OUTPUT OUTPUT OUTPUT (LEFT("hello", 4)) (RIGHT("Cat", 2)) (MID(LEFT("Karachi", 5), 2, 3)) ((MID(LEFT("Karachi", 5), 2, 3)) & "five") (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 : Huma Imad 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)) OUTPUT(ASC(str2)) // 12- LENGTH OF THE STRING IS DISPLAYED. //CONSIDER SPACE AS A VALID CHARACTER // ASCII VALUE OF THE LEFT MOST CHARACTER IS DISPLAYED 9608/21/M/J/16 Answer Teacher : Huma Imad 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 : Huma Imad 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 h e l l o Teacher : Huma Imad 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 DECLARE DECLARE DECLARE ThisString : STRING ThisChar : CHAR counter : INTEGER 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 : Huma Imad 56 | P a g e P2 Computer Science 9618 Pseudocode_Strings 9608/21/M/J/17 Teacher : Huma Imad 57 | P a g e P2 Computer Science 9618 Teacher : Huma Imad 58 | P a g e P2 Computer Science 9618 Past Paper Question Teacher : Huma Imad 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 Teacher : Huma Imad continued… 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 : Huma Imad 61 | P a g e P2 Computer Science 9618 Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 65 | P a g e P2 Computer Science 9618 SPECIMEN INSERT P2 Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 Integer) FUNCTION Add(num1 : Integer, num2 : Integer) RETURNS Integer 2 DECLARE Result :INTEGER 2 DECLARE Result :INTEGER 3 Result←num1+num2 3 Result←num1+num2 4 OUTPUT Result 4 OUTPUT Result 5 RETURN Result 5 END PROCEDURE 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 : Huma Imad 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 : Huma Imad 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 Teacher : Huma Imad END FUNCTION 73 | P a g e P2 Computer Science 9618 Procedure Pseudocode Teacher : Huma Imad 74 | P a g e P2 Computer Science 9618 Function(returns exactly one value) Pseudocode Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 78 | P a g e P2 Computer Science 9618 Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 83 | P a g e P2 Computer Science 9618 Parameter passing by value/ by reference _________________________________________________________________________ Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 90 | P a g e P2 Computer Science 9618 Arrays 1D Array page 212 text book 2D Array page 218 text book Teacher : Huma Imad 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 Lower Bound Upper Bound 1 46.87 2 21.50 3 43.00 4 67.00 5 24.00 Teacher : Huma Imad Array element Index/ subscript 92 | P a g e 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 Average←Total/5 OUTPUT “Average is” , Average Teacher : Huma Imad Variable Prices Each new value overwrites the previous value 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 Total←0 Average←0 For count←1 to 5 Input Prices[count] 20.5 37.9 60 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 : Huma Imad 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 : Huma Imad 95 | P a g e P2 Computer Science 9618 Q. Write statement to output the 7th number Output Num[7] Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 98 | P a g e P2 Computer Science 9618 Example 1 D array DECLARE DECLARE DECLARE DECLARE DECLARE Num: ARRAY[1:5] OF Integer Item : INTEGER Index : INTEGER Found : BOOLEAN 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 : Huma Imad 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 : Huma Imad 100 | P a g e P2 Computer Science 9618 'Search in an Array ..... Input what to search PROCDEURE SEARCH( ) DECLARE Item : INTEGER DECLARE Index : INTEGER DECLARE Found : BOOLEAN //LOCAL Variables 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 Multiple Search Result (Loop continues from lower bound to upper 1 14 2 25 3 70 4 44 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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]← "" ENDFOR Parameters End PROCEDURE PROCEDURE MyProgram() DECLARE Details[5] : String //Call to a procedure/Subroutine Call InitialiseArray(Details) End PROCEDURE Teacher : Huma Imad Arguments 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 114 | P a g e P2 Computer Science 9618 Compare only n-1 elements in the next pass 1 2 3 4 5 6 7 n Maxlndex – 1 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 : Huma Imad 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 : Huma Imad 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 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. 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 : Huma Imad 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 nn-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 : Huma Imad 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 [4] John 65sdf7@gmail.com 15/05/2011 C3482-B [5] Sahil weds@gmail.com 01/01/2016 C3432-V [3] 2D Array Details[1:5,1:4] indicates rows 1 to 5 and columns 1 to 4 1 row represents 1 record Element 01/01/2019 At Index [5,3] 2D array is a grid or a Table Data type That is (Row,Column) All elements in an array are of the same data type Teacher : Huma Imad 119 | P a g e P2 Computer Science 9618 2D ARRAY PROCEDURE TwoDArray() DECLARE Num:ARRAY [1:2, 1:4] OF INTEGER DECLARE DECLARE DECLARE DECLARE Row : INTEGER Col : INTEGER Item : INTEGER 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 : Huma Imad 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 //PROCEDURE header PROCEDURE TEST(DETAILS:ARRAY OF String) Parameter passing of 1D and 2D array is identical in pseudocode. //Call to a PROCEDURE Call TEST(Details) Teacher : Huma Imad 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 : Huma Imad 122 | P a g e P2 Computer Science 9618 Practice question: Q5 9608/23/M/J/15 Trace table (1D & 2D) Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 126 | P a g e P2 Computer Science 9618 Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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, other key for Yes") INPUT options press any UNTIL options = ‘N’ CLOSEFILE(“TESTFILE.txt”) Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 133 | P a g e P2 Computer Science 9618 PROCEDURE WriteOperation(FileName as STRING) //Corresponding CALL is as follows CALL WriteOperation ("Students.txt") Teacher : Huma Imad 134 | P a g e P2 Computer Science 9618 9608/21/O/N/17 Teacher : Huma Imad 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 : Huma Imad 136 | P a g e P2 Computer Science 9618 Teacher : Huma Imad 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 Onion 23.56 (a)PROCEDURE ReadNow(FileName :STRING ) DECLARE ID: STRING DECLARE Description: STRING DECLARE StrPrice :STRING DECLARE Price:REAL OPENFILE(FileName FOR READ) 2456 WHILE NOT EOF(FileName) READFILE (FileName, ID) OUTPUT (“ID IS ” & ID) Mango 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 : Huma Imad 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) StrPriceRIGHT(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 4 +x 34.50 +5 LENGTH(data)=4+x+5 Apply formula x = LENGTH(data)-(4+5) x = LENGTH(data) -9 Teacher : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 Found False FOR READ) 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 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 : Huma Imad 149 | P a g e