TABLE OF CONTENTS http://britishstudentroom.wordpress.com/ INTRODUCTION TO PROGRAMMING .................................................................. 1 SELECTION S TATEMENTS ................................................................................ 10 LOOP STATEMENTS ........................................................................................ 2 4 ARRAYS ......................................................................................................... 36 TRACING ....................................................................................................... 43 CODE ERRORS ............................................................................................... 64 DATABASES ................................................................................................... 7 5 DEFINITIONS ................................................................................................. 100 THEORY QUESTIONS .................................................................................... 109 1 http://britishstudentroom.wordpress.com/ http://britishstudentroom.wordpress.com/ Introduction to programming Definition of a program: A list of instructions that does a specific task. Example: Write a program that reads two numbers from the user and print out their sum. In other words, we need to write a program to solve the following equation: Z=A+B Solution: To write the program we go through four phases: 1 Analysis 2 Design 3 Implementation 4 Testing 1.1 Analysis In the analysis phase we try to figure out what are the inputs of the program, processing that it should do and the outputs it shall produce. Back to our program: Inputs: A, B Processing: Z = A + B Output: Z 1 http://britishstudentroom.wordpress.com/ Introduction to programming Operators Types of operators: 1 Arithmetic operators 2 Logic operators 3 Assignment operator Arithmetic Operators The following table shows the various Arithmetic operators and what they do: Arithmetic operators Operator Symbol Description Multiplication * Division / Divides the left operand by the right operand Example: x/y Subtraction - Subtracts the right operand from the left operand Example: x - y Addition + Adds the left operand to the right operand Example: x + y Power ^ Raises the left operand to the power of the right operand Example: ! ! is written as x ^ y Multiplies the left operand by the right operand. Example: x * y Logic Operators The following table shows some Logic operators: Comparison Operators Operator Symbol Greater than > Less than < Equal = Greater than or equal to >= Less than or equal to <= Not equal to <> 2 http://britishstudentroom.wordpress.com/ Introduction to programming Assi gnment Operator This operator assigns a value or an expression to a variable. The symbol used for this operator is an arrow pointing left: Examples of assignment operator: Cost ← 10 Price ← Cost * 2 Tax ← Price * 0.14 Service ← Price * 0.12 PaidAmount ← Tax + Service 1.2 Design After the analysis phase is done, we design the Algorithm. An algorithm is a step-by-step solution to a given problem. We design algorithm using one of two methods: Flowcharts Pseudocode 1.2.1 Flowcharts Definition: Diagram that designs the steps of a program by using a standard set of symbols joined by lines to show the direction of flow. Flowcharts have some shapes that we use to draw the diagram with: Shape Name Description Start/End An oval represents a start or end point Arrows A line is a connector that shows the relationship between the shapes 3 http://britishstudentroom.wordpress.com/ Introduction to programming Input / Output A parallelogram represents output or input Process A rectangle is a process Decision A diamond indicates a decision Solving our problem using the flowchart design: Z = A + B 4 http://britishstudentroom.wordpress.com/ Introduction to programming 1.2.2 Pseudocode Definition: Uses English words and mathematical notations to design the steps of a program. INPUT Keywords To allow the user to input a value we use one of two keywords: INPUT READ OUTPUT Keywords To show the user the value of a variable we use one two keywords: OUTPUT PRINT Writing the program in pseudocode: O U T P U T “ P l e a s e en t e r t w o n u m b e r s t o a d d ” INPUT A INPUT B Z ← A + B OUTPUT Z 1.3 Implementation After designing the algorithm, the algorithm is transformed into code using a programming language. Examples of programming languages: C++ Java Python 5 http://britishstudentroom.wordpress.com/ Introduction to programming 1.4 Testing The last phase of the programming, this phase is done after implementation by testing how the program works, we will discuss this later. Variables Definition: A variable is a named memory location that stores a value that can change during the execution of a program. Rules for naming variables: Variable names cannot contain spaces Variable names cannot start with numbers Variable name should not be a keyword of pseudocode Variable names should be meaningful to the value it stores Examples of valid variable names: number total c o u n t c o u n t 1 count_students countStudents Examples of invalid variable names: count 1 c o u n t OUTPUT students 6 http://britishstudentroom.wordpress.com/ Constants Definition: A constant is a named memory location that stores a value that does not change during the execution of a program. Note that: Constants have the same naming rules as variables. Data Types Computers need to know the data type for every variable, to make the processing on this variable as effective as possible. The following table shows the data types used in programs: Data type Definition Examples Integer A positive or negative whole number be used in mathematical operations 150, -100, 0 Real A positive or negative number that has a fractional part that can be used in mathematical operations 100.5, -15.2 Char A single character from the keyboard H String A sequence of characters Boolean Data with two possible values Hello World, A312_@odq TRUE/FALSE 7 http://britishstudentroom.wordpress.com/ Introduction to programming D eclaration When declaring a variable you have to do two Give your variable a valid name Give it a data type things: Declaration syntax in pseudocode: DECLARE [VARIABLE NAME] : [VARAIBLE DATA TYPE] The complete pseudocode solution: DECLARE Num1: REAL DECLARE Num2: REAL DECLARE Sum: REAL O U T P U T “ P l e a s e ent er t w o n u m b e r s t o a d d ” INPUT Num1 INPUT Num2 Sum Num1 + Num2 O U T P U T “The number is ”,Su m 8 http://britishstudentroom.wordpress.com/ Introduction to programming Sequential Exercise 1 Write a program to input length, width and depth of a pool. The program should output the volume and price of pool. The price of the pool is dependent on the volume: $1 per 100 cm 3 . 2 Write a program that inputs a mark and raw score. The program should output the percentage 3 Write a program that converts a person’s height in inches to centimeters and their weight in stones into kilograms [1 inch = 2.54 cm and 1 stone 6.364 kg] 4 Write a pseudocode that inputs days from the user. The program should output how many weeks and days. A function INT( ) should be used. The function takes a number and returns the whole number . For example INT(1.5) = 1 5 Write a program that inputs diameter and depth of a round concrete slab in mm. The price of one slab is $0.05 per 10000 mm 3 . HINT: Volume of a cylinder = π*radius 2 *depth 9 2 http://britishstudentroom.wordpress.com/ Part I IF..THEN..ENDIF http://britishstudentroom.wordpress.com/ Conditional Statements Definition of Sequential statements: Statements are executed one after another according to their order. Definition of Conditional/Selection statements: Selective statement(s) are executed depending on meeting certain criteria. Purpose of Conditional statements: To allow different paths through a program depending on meeting certain criteria. 2.1 IF .. THEN .. ELSE .. ENDIF: Definition: A conditional structure with different outcomes for true and false. Purpose: It allows for checking complex conditions. IF [CONDITION] THEN // What to do if the condition is true ELSE // What to do if the condition is false ENDIF Example 2.1.1: Design a program, using pseudo-code and flowchart, which takes a number as input and outputs whether the number is zero or non-zero. Pseudo-code Solution: DECLARE num: REAL OUTPUT “Enter a number” INPUT num IF num = 0 THEN OUTPUT “The number is zero” ELSE OUTPUT “The number is non-zero” ENDIF 10 http://britishstudentroom.wordpress.com/ Conditional Statements Flowchart Solution: Example 2.1.2: Design a program, using pseudo-code and flowchart, which takes a number as input and outputs whether the number is positive or negative or zero. Pseudo-code Solution: DECLARE num: REAL OUTPUT “Enter a number” INPUT num IF num > 0 THEN OUTPUT “The number is positive” ELSE IF num < 0 THEN OUTPUT “The number is negative” ELSE OUTPUT “The number is negative” ENDIF ENDIF 11 http://britishstudentroom.wordpress.com/ Conditional Statements Flowchart Solution: 12 http://britishstudentroom.wordpress.com/ Conditional Statements Validation Often we need to check that the user has not entered unacceptable data, take the example of dividing two numbers, you cannot divide by zero. So we have to anticipate mistakes users might do, this is called Validation. Example: Read two numbers and divide them Z = A / B. Pseudo-code Solution: DECLARE Num1,Num2,Result: REAL INPUT Num1,Num2 IF Num2 = 0 THEN OUTPUT “MATH ERROR” ELSE Result Num1 / Num2 OUTPUT Result ENDIF 13 http://britishstudentroom.wordpress.com/ Conditional Exercise 1 1 Design a program, using pseudocode and flowchart, which inputs from the user length of a square. The program calculates the perimeter of the square. AN ERROR MESSAGE SHOULD BE DISPLAYED WHEN NEEDED. 2 Design a program using pseudocode which inputs a number from the user and outputs the square root. Use a function called Sqrt, which takes a number and returns the square root of the number DONOT FORGET TO VALIDATE THE NUMBER. 3 Design a program, using pseudocode and flowchart, which takes a number between 1 and 7 and outputs the day name (Day 1= Sunday). A n error message should be displayed if the user enters invalid day number 4 Design a program, using pseudocode and flowchart, that takes two numbers and the operation as input and performs a basic operation (+, - or *) as per user requires. A n error message should be displayed if the user enters invalid operation 14 2 http://britishstudentroom.wordpress.com/ Part II IF..THEN..ENDIF http://britishstudentroom.wordpress.com/ Conditional Statements Example 2.1.3: Design a program, using pseudo-code and flowchart, which takes a number and prints “In range” if the number is between 1 and 10 inclusive, otherwise the program outputs “Outside range”. Pseudo-code Solution: DECLARE Num: REAL O U T P U T “Enter a number” INPUT Num IF Num >= 50 AND Num <= 100 THEN O U T P U T “In range” ELSE O U T P U T “Outside range” ENDIF Flowchart Solution: 15 http://britishstudentroom.wordpress.com/ Conditional Statements Example 2.1.4: Design a program, using pseudocode and flowchart, which takes marks in an exam as input and outputs the grade according to the following grade boundaries: Mark Grade 90 - 100 A 80 – 89 B 70 – 79 C < 70 F Pseudo-code Solution: DECLARE Mark: INTEGER O U T P U T “Enter the mar k” INPUT Mark IF Mark >= 90 AND Mark <= 100 THEN OUTPUT “A” ELSE IF Mark >= 80 AND Mark <= 89 THEN OUTPUT “B” ELSE IF Mark >= 70 AND Mark <= 79 THEN OUTPUT “C” ELSE IF Mark >= 0 AND Mark <= 69 THEN OUTPUT “F” ELSE O U T P U T “Invalid m a rk” ENDIF ENDIF ENDIF ENDIF 16 http://britishstudentroom.wordpress.com/ Conditional Statements Flowchart Solution: 17 http://britishstudentroom.wordpress.com/ Conditional Statements Conditional Exercise 2 1 Write a pseudocode that reads a number and prints “Correct range” in case the number is between 30 and 50 exclusive. Otherwise the program outputs “Wrong range”. 2 Extend the above pseudocode so that if the number is in wrong range, a message will be displayed saying whether the number is above range or below range. 3 Design a program, using pseudocode and flowchart, which takes three numbers from the user and outputs the minimum. 4 Design a program, using pseudocode and flowchart, that takes the salary of 3 months (salaries cannot be negative) as inputs and output the financial status according to the following table: Average salary of 3 months Financial Status >10,000 Rich 2,000 – 10,000 Moderate <2,000 Poor DO NOT VALIDATE THE SALARIES. 5 Design a program, using pseudocode and flowchart, that: T akes from the user the number of hours worked this week and their hourly rate of pay. The program should calculate and output the gross pay. If the number of hours worked is more than 40, then the extra hours are paid 1.5 times the rate. The program should stop and display an error message if the number of hours worked is not in the range of 0 to 60 OR if the user entered a negative hourly rate of pay. 18 2 http://britishstudentroom.wordpress.com/ Part III CASE..OTHERWISE..ENDCASE http://britishstudentroom.wordpress.com/ Conditional Statements 2.2 CASE .. OF .. OTHERWISE .. ENDCASE: Definition: A conditional structure that allows selection to be made based on value of a variable. Purpose: Used to test for a large number of discrete values. CASE [ANY VARIABLE] OF 1: // do something if the variable equals 1 2: // do something if the variable equals 2 OTHERWISE: // do something if the variable doesn’t equal any of the cases. ENDCASE Example 2.2.1: Design a program, using pseudocode and flowchart, which takes a course number as input and outputs the corresponding course name according to this table: Course Number Course Name 1 Computer Science 2 ICT 3 Math 4 Biology Pseudocode Solution: DECLARE CourseNo: INTEGER OUTPUT “Enter the course number“ INPUT CourseNo CASE CourseNo OF 1: OUTPUT “Compute 2: OUTPUT “ICT” Science” 3: OUTPUT “Math” 4: OUTPUT “Biology” OTHERWISE OUTPUT “Invalid Course number” ENDCASE 19 http://britishstudentroom.wordpress.com/ Conditional Statements Flowchart Solution: 20 http://britishstudentroom.wordpress.com/ Conditional Statements E x a m p l e 2 .2.2: Write pseudocode that takes two numbers as input and performs any of the basic operation (+, -, *, /) as per user requires. Solution: DECLARE FirstNumber, SecondNumber, Result: INTEGER DECLARE Operation: CHAR OUTPUT “Enter the first number” INPUT FirstNumber OUTPUT “Enter the second number” INPUT SecondNumber OUTPUT “Enter the operation” INPUT Operation CASE Operation OF ‘+’: Result FirstNumber + SecondNumber OUTPUT Result ‘-’: Result FirstNumber - SecondNumber OUTPUT Result ‘*’: Result FirstNumber * SecondNumber OUTPUT Result ‘/’: Result FirstNumber / SecondNumber OUTPUT Result OTHERWISE OUTPUT “Invalid operation” ENDCASE 21 http://britishstudentroom.wordpress.com/ Conditional Statements Conditional Exercise 3 1 Write a pseudocode that takes from user: length, width and depth of an object. The user also inputs the object code from the following table: Object code Object name 1 Square 2 Rectangle 3 Cylinder Output the volume of the object based on the user’s choice. HINT: Volume of cylinder: π*r 2*depth 2 Design a program, using pseudocode and flowchart, that takes three numbers from the user and prints the numbers in descending order. 3 Write a pseudocode that takes a number from the user and displays whether it’s a negative or zero (don’t output anything if it’s positive). 1 Write a pseudocode that inputs the savings of a bank client without interest rate. The program outputs the updated amount after applying interest according to the following criteria: If savings exceed 500,000, the interest rate is 10% If savings exceed 250,000, the interest rate is 5% If savings exceed 50,000, the interest rate is 2.5% Otherwise no interest is added If the user inputs a negative saving, an error message should be displayed and the pr ogr am stops without calculating the updated amount . 22 [6] http://britishstudentroom.wordpress.com/ Conditional Statements 4 Write a pseudocode that inputs the income of a worker without taxes. The program must output the updated amount after applying taxes according to the following criteria: Salary Tax Rate >10,000 50% 2,000 – 10,000 25% <2,000 0% Not e that the salary cannot b e less than 0 and not mo r e than 50,000 5 Write a pseudocode that reads two integer values (x and y), which should represent the coordinates of a point in a plane. Next, determine which quadrant the point belongs. If the point is at the origin print “Origin” If it’s exactly on the x-axis print “X-Axis” If it’s exactly on the y-axis print “Y-Axis” Otherwise print the name of the quadrant 23 3 http://britishstudentroom.wordpress.com/ Part I FOR..NEXT http://briishstudentroom.wordpress.com/ Loop Statements Definition of Iteration/Repetition: One or more statements are repeated till a test condition is met or whilst a test condition is TRUE. 3.1 FOR … TO … NEXT Definition: A loop structure that iterates a set number of times. FOR variable [initial value] TO [final value] // statement(s) to be repeated NEXT Example 3.1.1: Design pseudo-code and flowchart that prints the integers from 1 to 10. Pseudocode solution: FOR i 1 TO 10 OUTPUT i NEXT Flowchart solution: 24 http://briishstudentroom.wordpress.com/ Loop Statements E x a m p l e 3 .1.2: Write pseudo-code that prints the integers from 10 to 1. Pseudocode solution: FOR Count 10 TO 1 STEP -1 OUTPUT Count NEXT Totaling Definition: Totaling is a process of summing a list of number. Examples: Total Total + 5 Sum Sum + Num Example 3.1.3: Write pseudocode that reads a number N, and prints the sum of all the numbers between 1 and N. Pseudocode solution: DECLARE N,Sum: INTEGER O U T P U T “Enter the number ” INPUT N Sum 0 FOR i 1 TO N Sum Sum + i NEXT O U T P U T “T h e summat i on is: “, S u m 25 http://briishstudentroom.wordpress.com/ Loop Statements Counting Definition: Counting is the process of finding how many numbers/items are in a list. Examples: Count Count + 1 Count Count + 5 Count Count – 1 Example 3.1.4: Write pseudocode that inputs 50 numbers and counts the numbers that are greater than 100. Pseudocode solution: DECLARE Num,Count: INTEGER Count 0 FOR i 1 TO 100 OUTPUT “Enter the number” INPUT Num IF Num > 100 THEN Count Count + 1 ENDIF NEXT OUTPUT “The count of numbers greater than 100 is: “,Count 26 http://briishstudentroom.wordpress.com/ Loop Statements Example 3.1.5: Write pseudocode that reads 100 numbers and prints out their minimum. Pseudocode solution 1: DECLARE Min, Num: INTEGER Min 99999 FOR Counter 1 TO 100 O U T P U T “Enter number” INPUT Num IF Num < Min THEN Min Num ENDIF NEXT O U T P U T “ M i n i m u m n u m b e r enter ed is: “ , Mi n Pseudocode solution 2 (better solution): DECLARE Min, Num: INTEGER O U T P U T “Enter number” INPUT Num Min Num FOR Counter 1 TO 99 O U T P U T “Enter number” INPUT Num IF Num < Min THEN Min Num ENDIF NEXT O U T P U T “ M i n i m u m n u m b e r enter ed is: “ , Mi n 27 http://briishstudentroom.wordpress.com/ Loop Statements Example 3.1.6: Write pseudocode that reads 100 numbers and prints out their maximum. Pseudocode solution 1: DECLARE Max, Num: INTEGER Max -99999 FOR Counter 1 TO 100 O U T P U T “Enter number” INPUT Num IF Num > Max THEN Max Num ENDIF NEXT O U T P U T “M a x i m u m n u mb e r entered is: “,M a x Pseudocode solution 2 (better solution): DECLARE Max, Num: INTEGER O U T P U T “Enter number” INPUT Num Max Num FOR Counter 1 TO 99 O U T P U T “Enter number” INPUT Num IF Num > Max THEN Max Num ENDIF NEXT O U T P U T “M a x i m u m n u mb e r entered is: “,M a x 28 http://briishstudentroom.wordpress.com/ Loop Statements Loop Exercise 1 1 Write a pseudocode that prompts the user to enter a short message and the number of times it is to be displayed and then displays the message the required number of times 2 Write a pesudocode that reads 100 numbers from the user. Then it counts the numbers that in the range -100 to 35 inclusive. 3 Write a pseudocode that takes 5 numbers from the user and outputs the maximum. 4 Write a pseudocode to input 250 numbers. Count how many numbers are positive, how many are negative and how many are zeros. Then output the results. 5 Write a pseudocode that inputs 500 numbers and outputs how many of these numbers were whole numbers (integers). HINT: You may use INT(x) in your answer. For example, INT(3.8) gives the value 3 6 Write a pseudocode that reads a number and prints out its factorial. The factorial of a number is calculated by multiplying all the integers smaller than or equal to it until 1. 5! = 5 x 4 x 3 x 2 x 1 FACTORIAL CANNOT BE DONE ON A NEGATIVE NUMBER! 29 3 http://britishstudentroom.wordpress.com/ Part II WHILE..DO..ENDWHILE http://briishstudentroom.wordpress.com/ Loop Statements 3.2 WHILE ... DO ... ENDWHILE Definition: A loop that iterates whilst a specified condition exists Criteria is pre-tested (It has criteria check at the start) It may never run WHILE (CONDITION) DO // Code to repeat in here. ENDWHILE Example 3.2.1: Write pseudocode that reads set of numbers from the user until the user enters a non-positive number (Less than or equal to zero). The program calculates and displays the total of these numbers. Pseudocode solution: DECLARE Num: REAL DECLARE Sum: REAL Sum 0 OUTPUT “Input a number” INPUT Num WHILE Num >= 0 DO Sum Sum + Num OUTPUT “Input another number” INPUT Num ENDWHILE OUTPUT “The sum of numbers entered is: “,Sum 30 http://briishstudentroom.wordpress.com/ Loop Statements Example 3.2.2: Rewrite the pseudocode given below by using WHILE...DO...ENDWHILE loop DECLARE Num, Total : INTEGER INPUT N Total 0 FOR i 1 TO N Total Total + i NEXT OUTPUT Total Pseudocode solution: DECLARE Num, Total, i : INTEGER INPUT Num Total 0 i 1 WHILE i <= Num DO Total Total + i i i+1 ENDWHILE OUTPUT Total 31 3 http://britishstudentroom.wordpress.com/ Part III REPEAT..UNTIL http://briishstudentroom.wordpress.com/ Loop Statements 3.3 REPEAT … UNTIL Definition: A loop that iterates until a condition is met Criteria is post-tested (It has criteria check at the end) It iterates at least once REPEAT // code to repeat UNTIL (STOPPING CONDITION) Differences between REPEAT ... UNTIL and WHILE ... DO ... ENDWHILE: In WHILE the criteria is pre-tested but in REPEAT..UNTIL the criteria is posttested WHILE may never run while REPEAT UNTIL runs at least once WHILE iterates whilst a condition is TRUE but REPEAT UNTIL iterates till a condition is TRUE Example 3.3.1: Design pseudocode that inputs set of until the user enters 0. Calculate and display the total. Pseudocode solution: DECLARE Sum: REAL DECLARE num: REAL Sum 0 REPEAT OUTPUT “Enter a number to add” INPUT num Sum Sum + num UNTIL num = 0 OUTPUT “The total of the numbers entered: “,Sum 32 http://briishstudentroom.wordpress.com/ Loop Statements Example 3.3.2: Write a pseudocode that will take anything as input and will display it as output until “Stop” or “End” is pressed Pseudocode solution: REPEAT OUTPUT “Enter a number, value, character or symbol to display” INPUT anyvalue OUTPUT anyvalue UNTIL anyvalue = “End” OR anyvalue = “Stop” Example 3.3.3: Rewrite the pseudocode given below by using REPEAT .. UNTIL loop DECLARE Num, Total : INTEGER INPUT N Total 0 FOR i 1 TO N Total Total + i NEXT OUTPUT Total Pseudocode solution: DECLARE Num, Total, i : INTEGER INPUT Num Total 0 i 1 REPEAT Total Total + i i i+1 UNTIL i > N OUTPUT Total 33 http://briishstudentroom.wordpress.com/ Loop Statements IMPORTANT: Both REPEAT..UNTIL and WHILE..DO..ENDWHILE loops are called Condition Controlled Loops Purpose of Iteration/Repetition statements: To repeat same or similar code a number of times, which allows for shorter code. Loop Exercise 2 1 Write a pseudocode using that asks the user to enter an age between 1 and 99 inclusive and will validate the input. It should repeatedly ask the user for the age until the user enters a valid age. The age is then displayed. DO THIS QUESTION ONCE WITH WHILE AND ONCE WITH REPREAT UNTIL 2 Write a pseudocode that asks the user to input N weights from the user. The program then prints the average of those weights. VALIDATE THE WEIGHTS (CANNOT BE NEGATIVE OR MORE THAN 250) DON’T FORGET TO VALIDATE N 3 4 Write a pseudocode that: Inputs numbers till the user inputs -1 Totals the numbers that are between 40 and 80 (inclusive) Suppose you have designed a game that only allows people to play it if they are over 12 years of age. Write a pseudocode that reads ages of players until the user enters zero, and prints out the number of players who can play the game, and the number of players who cannot. 34 http://briishstudentroom.wordpress.com/ Loop Statements 5 Rewrite the following pseudocode using WHILE .. DO .. ENDWHILE and REPEAT.. UNTIL loop: INPUT Num Max Num FOR Counter ← 1 TO 49 INPUT Num IF Num > Max THEN Max Num ENDIF NEXT OUTPUT “The maximum number is :”,Max 6 Write a pseudocode that multiplies two numbers entered by the user without using the multiplication operator. 7 Write a pseudocode that inputs username and password of an account on a social network website. In order to return the password for an account, a function called GetPassword(username) is used. This function takes a username as a parameter and returns the corresponding password. The program displays “Success” if the password of the account is correct If the password is incorrect, the program prompts the user to re-enter the password but only for 3 attempts ASSUME THAT THE USERNAME ENTERED EXISTS IN THE SYSTEM 35 4 http://britishstudentroom.wordpress.com/ http://britishstudentroom.wordpress.com/ Arrays 4.1 Arrays Consider the following example: Example 4.1: Write a pseudocode that reads 5 numbers from the user and prints them in reverse order. Pseudocode solution: DECLARE Num1,Num2,Num3,Num4,Num5: INTEGER INPUT Num1 INPUT Num2 INPUT Num3 INPUT Num4 INPUT Num5 OUTPUT Num5 OUTPUT Num4 OUTPUT Num3 OUTPUT Num2 OUTPUT Num1 This would be okay if you want to reverse few integers, but if you want to reverse 100 integers, maybe a 1000. We have to use something called an Array. Array Definition: A data structure that holds a number of elements of the same data type. Pseudocode declaration: DECLARE Numbers[1:N] : INTEGER N is the number of elements in the array 36 http://britishstudentroom.wordpress.com/ Arrays Accessing an element in an array: In order to access an element of the array, the index should be specified. For example: OUTPUT Numbers[1] This statement will output the value stored in the first place in the array Nu mber s Example 4.2: Write pseudocode that reads 1000 numbers from the user and prints them in reverse order. Pseudocode solution: DECLARE Numbers[1: 1000] : INTEGER F O R Counter 1 T O 1000 I N P U T N u mb er s[ C ou nt er ] NEXT F O R Counter 1000 T O 1 S T EP -1 O U T P U T N umbers[Counter ] NEXT Purpose of using arrays: To store multiple values under the same identifier making the code shorter Allows for simpler programming 37 http://britishstudentroom.wordpress.com/ Example 4.3: Write pseudocode that reads the ages of a 100 student from the user and stores them. Then use the stored values to find the count of students who are older than 18 years. Pseudocode solution: DECLARE Ages[1:100]: INTEGER DECLARE Count: INTEGER FOR i 1 TO 100 INPUT Ages[i] NEXT Count 0 FOR i 1 TO 100 IF Ages[i] > 18 THEN Count Count + 1 ENDIF NEXT OUTPUT “Count of students older than 18 is: ”,Count 38 http://britishstudentroom.wordpress.com/ Arrays 4.1 Associative Arrays Sometimes you might need to store two values about a certain thing, for example, the name and age of all students. In this case we’d need to have two arrays, one array for storing the names, and one for storing the ages. Example 4.4: Write pseudocode that reads the names and marks of 50 students, stores them and then output the name of the student who scored the highest grade. Marks are out of 100. Pseudocode solution: DECLARE Names[1:50]: STRING DECLARE Marks[1:50]: INTEGER DECLARE MaximumIndex, MaximumMark: INTEGER MaximumMark -1 FOR i 1 TO 50 OUTPUT “Enter the name of the student ” INPUT Names[i] REPEAT OUTPUT “Enter the mark of the student ” INPUT Marks[i] UNTIL Marks[i]>=0 and Marks[i]<=100 NEXT FOR i 1 TO 50 IF Marks[i] > MaximumMark THEN MaximumMark Marks[i] MaximumIndex i ENDIF NEXT OUTPUT “Student with highest mark is : “,Names[MaximumIndex] OUTPUT “The highest mark is: “,MaximumMark 39 http://britishstudentroom.wordpress.com/ Arrays Arrays Exercise 1 Write a pseudocode that inputs and stores one temperature per day for a year (365 days). Display: The maximum temperature in the first 20 days The maximum temperature in the last 20 days 2 Write pseudocode that will take 10 student names and 10 student ages and print the name of the student with the maximum age. 3 A data logger records the temperature on a roof of a school twice a day, at midday and midnight. Task 1: Input and store the temperatures recorded for 30 days. o Y o u must store the temperatures in t wo arrays, o ne for mi dday temperatures and one for midnight temperatures. All temperatures should be validated and the user should repeatedly re-enter the temperatures if they are invalid. o Assume that a valid temperature is between -20 and 100 [5] Task 2: Calculate and output the average temperature for midday Calculate and output the average temperature for midnight [5] Task 3: Select the day with the highest midday temperature Select the day with the lowest midnight temperature Don’tforgettodisplayappropriatemessagesforinputandoutput. 40 [5] http://britishstudentroom.wordpress.com/ Arrays 4 TASK 1 Input and store the names of 500 employees in a company. Also, input and store their genders and salaries. Gender is either “Male” or “Female” Minimum salary is $1000 and maximum salary is $40,000 TASK 2 The program should display the name and salary of the top paid male worker and the top paid female worker. TASK 3 Determine and output who has higher average salary, male or female workers. 5 The height of buildings and number of floors in buildings were being analyzed. Task 1: Inputs the heights and number of floors of 200 buildings o Heights should not be negative o Number of floors cannot be less than 1 or more than 50 Task 2: Calculate and output the average height of all the buildings Calculate and output the number of buildings with more than 50 floors Task 3: The user inputs number of floors and the program searches for buildings that has the number of floors specified by the user and outputs the height of the tallest one from those buildings. (Note that: not all buildings will be considered when calculating the maximum) 41 http://britishstudentroom.wordpress.com/ Arrays 6 Set up a voting system that chooses between 4 candidates. 50 students will vote. Task 1: Input and store the names of the 4 candidates Output the candidate names with a number (1,2,3 or 4) beside each name Set up another array for voting and set its value to zero Task 2: Each student inputs a choice between 1,2,3 or 4 Update the vote of the appropriate candidate Output the name of the candidate voted for or output ‘invalid vote’ if a vote is rejected Task 3: Display the name of the winner and the number of votes. 42 5 http://britishstudentroom.wordpress.com/ http://britishstudentroom.wordpress.com/ Program Tracing 1 43 http://britishstudentroom.wordpress.com/ Program Tracing 44 http://britishstudentroom.wordpress.com/ Program Tracing 2 45 http://britishstudentroom.wordpress.com/ Program Tracing 46 http://britishstudentroom.wordpress.com/ Program Tracing 3 47 http://britishstudentroom.wordpress.com/ Program Tracing 48 http://britishstudentroom.wordpress.com/ Program Tracing 4 49 http://britishstudentroom.wordpress.com/ Program Tracing 50 http://britishstudentroom.wordpress.com/ Program Tracing 5 51 http://britishstudentroom.wordpress.com/ Program Tracing 6 52 http://britishstudentroom.wordpress.com/ Program Tracing 7 53 http://britishstudentroom.wordpress.com/ Program Tracing 54 http://britishstudentroom.wordpress.com/ Program Tracing 8 55 http://britishstudentroom.wordpress.com/ Program Tracing 9 56 http://britishstudentroom.wordpress.com/ Program Tracing 57 http://britishstudentroom.wordpress.com/ 10 Program Tracing 58 http://britishstudentroom.wordpress.com/ Program Tracing 59 http://britishstudentroom.wordpress.com/ Program Tracing 11 60 http://britishstudentroom.wordpress.com/ Program Tracing 61 http://britishstudentroom.wordpress.com/ 12 Program Tracing 62 http://britishstudentroom.wordpress.com/ \ 13 Program Tracing This pseudocode inputs the weight of items in kilograms to be loaded on a trailer. Any item over 25 kilograms is rejected. The trailer can take up to 100 kilograms. TotalWeight 0 Rej ect 0 REPEAT INPUT Weight IF Weight > 25 THEN Reject Reject + 1 ELSE TotalWeight TotalWeight + Weight ENDIF U N T IL TotalWeight > 100 TotalWeight TotalWeight – Weight OUTPUT “Weight of items ”’ TotalWeight ,” Number of items rejected “, Reject 63 6 http://britishstudentroom.wordpress.com/ http://britishstudentroom.wordpress.com/ Code Errors 1 64 http://britishstudentroom.wordpress.com/ Code Errors 2 65 http://britishstudentroom.wordpress.com/ Code Errors 3 66 http://britishstudentroom.wordpress.com/ Code Errors 4 67 http://britishstudentroom.wordpress.com/ Code Errors 5 68 http://britishstudentroom.wordpress.com/ Code Errors 6 69 http://britishstudentroom.wordpress.com/ Code Errors 7 70 http://britishstudentroom.wordpress.com/ Code Errors 8 71 http://britishstudentroom.wordpress.com/ ] Code Errors 9 72 http://britishstudentroom.wordpress.com/ Code Errors 73 http://britishstudentroom.wordpress.com/ Code Errors 10 74 7 http://britishstudentroom.wordpress.com/ http://britishstudentroom.wordpress.com/ Databases 1. Data types used in database Data Type Examples Number 12, 45, 1274, 653.12, -35.86 Currency £12.45, -£0.01, €999.00, $5500 Text DOG, ABC123, enquiries@bbc.co.uk Boolean TRUE/FALSE and YES/NO Date 25/10/2007, 12 Mar 2008, 10-06-08 2. Selecting Data Types When we input data to a database, we must analyse it and select appropriate data types for each field: Student Name: Ben Smith Text Student Number: 1234 Number Date of Birth: 10 July 1998 Date Year Group: 6 Number Special Diet: Yes Boolean Height: 1.67 Number Fees Paid: $ 1500 Currency 3. Definition of Database A structured collection of related data that allows people to extract information in a w a y that me et s their needs. Databases are very useful in preventing data problems occurring because: Data is only stored once - no data duplication If any changes are made it only has to be done once - the data is consistent Same data is used by everyone 75 http://britishstudentroom.wordpress.com/ Databases 4. The structure of a database Inside a database, data is stored in tables, which consists of many fields and records. The following table shows some database elements and their definitions: Term Definition Examples Table/File A collection of related records Table of students For a student the fields could include: Student name Student ID Age Address Gender Field A column that contains one specific piece of Field Name Title given to each field and is always placed at Record A row within a table that contains data about a Details (all information) of single item, person or event one student Primary Key/ A field that contains unique data and can’t be Key Field repeated for more than one once information and has one data type the top row of table 76 Student ID field http://britishstudentroom.wordpress.com/ Eng. Omar El Safty Databases Note that: Primary keys are used to: To be sure that each record can be found easily To prevent duplication of records 77 http://britishstudentroom.wordpress.com/ Databases 5. Query By Example In order to select data with some specific criteria from a database, we use queries. Let’s consider the following example: The following is a query-by-example grid: Here, we enter the name of fields that are involved in our search We state here whether we need sorting (Ascending/Descending) by a specific field We write the table name of each field. In our case it’s PROPERTY Here, we write our search criteria 78 We tick the fields that we need to show http://britishstudentroom.wordpress.com/ Databases The following query-by-example grid selects and shows the Prices and Brochure numbers of all houses with more than 1 bathroom and more than 2 bedrooms in ascending order of Price. The results shown are: 399,000 H13 450,000 H10 6. Validation Definition: The automated checking by a program that data to be entered is sensible. Examples of validation checks: Type Presence Range Length Character Format Check digit 79 http://britishstudentroom.wordpress.com/ Databases 5.1 Type Check Definition: Checks that the data entered has the appropriate data type. Example: A person’s age should be a number not text. 5.2 Presence Check Definition: Checks that some data has been entered and the value has not been left blank. Example: An email address must be given for an online transaction. 5.3 Range Check Definition: It checks that only numbers within a specified range are accepted. Example: Exam marks between 0 and 100 inclusive. 5.4 Length Check Definition It checks that data contains an exact number of characters Example: A password with exactly 8 characters in length. If the password has fewer or more than 8 characters, it will be rejected. 80 http://britishstudentroom.wordpress.com/ Databases 5.6 Character Check Definition: It checks that a string of characters does not contain any invalid characters or symbols. Examples: A name would not contain characters such as % A telephone number would only contain digits. 5.7 Format Check Definition: It checks that the characters entered conform to a pre-defined pattern. Example: A company with IDs that start with MS then three numbers would have a format of MS### 5.8 Check Digit Definition: A digit that it is calculated from all the other digits and appended to the number. They can usually detect the following types of error: An incorrect digit entered o For example 5327 entered instead of 5307 Transposition errors where two numbers have changed order o For example 5037 instead of 5307 Removing a digit o For example 537 instead of 5307 Putting an extra digit o For example: or 53107 instead of 530 81 http://britishstudentroom.wordpress.com/ Databases Example: 82 http://britishstudentroom.wordpress.com/ Databases 7. Data Verification Definition: Checking that the data has not changed during input to a computer or during transfer between computers. Purpose: To ensure the accuracy of transcription. Verification methods include: Screen/Visual check Double entry Screen/Visual Check Definition: Data is compared visually with the source document by a user The user is asked to confirm that the data entered is same as original If user finds a difference, the data is re-entered Double Data Entry Definition: Data is entered twice (sometimes by two different people) A computer checks that both entries are equal If they are not equal, an error message requesting to re-enter the data is displayed Note that: Double data entry is different from Proofreading! Proofreading is reading through the document, without referring to the original source document, to identify grammatical and spelling mistakes. 83 http://britishstudentroom.wordpress.com/ Databases 8. Testing Data Definition: Data used to check that a computer program responds correctly to correct and incorrect data. Normal Definition Examples Correct data that should be accepted The month can be any whole Data number in the range of 1 to 12 All the following values are not allowed as inputs for the month: Data outside the limits of acceptability, Abnormal or wrong type of data, and should be Data r ej ected Negative numbers Any value greater than 12 Letters or non-numeric data Non-integer values (e.g., 3.5,10.75, etc.) Extreme Data Data at the limits of acceptability and it The extreme values of month can shoul d b e accept ed be either 1 or 12 Boundary Rejected Data The rejected data on the boundaries Boundary rejected values of month can be either 0 or 13 84 http://britishstudentroom.wordpress.com/ Databases Database Exercise 1 85 http://britishstudentroom.wordpress.com/ Databases 2 86 http://britishstudentroom.wordpress.com/ Databases 3 87 http://britishstudentroom.wordpress.com/ Databases 4 88 http://britishstudentroom.wordpress.com/ Databases 89 http://britishstudentroom.wordpress.com/ Databases 5 90 http://britishstudentroom.wordpress.com/ Databases 6 91 http://britishstudentroom.wordpress.com/ Databases 7 92 http://britishstudentroom.wordpress.com/ Databases 8 93 http://britishstudentroom.wordpress.com/ Databases 94 http://britishstudentroom.wordpress.com/ Databases 9 95 http://britishstudentroom.wordpress.com/ Databases 10 96 http://britishstudentroom.wordpress.com/ Databases 97 http://britishstudentroom.wordpress.com/ Databases 11 98 http://britishstudentroom.wordpress.com/ Databases 12 99 8 http://britishstudentroom.wordpress.com/ http://britishstudentroom.wordpress.com/ Definitions 1. P r o g r a m Definition: A list of instructions that does a specific task It can be written in High Level language or Low Level Language 2. P se ud oc o de Definition: Method that uses English words and mathematical notations to design the steps of a program. 3. Flowcharts Definition: Diagram that designs the steps of a program by using a standard set of symbols joined by lines to show the direction of flow. 4. Trace Table Definition: Table that can be used to record the results from each step in an algorithm It is used to record the value of a variable each time it changes 5. Variable Definition: A named data store that contains a value that can change during the execution of a program. 6. Constant Definition: A named data store that contains a value that does not change during the execution of a program. 100 http://britishstudentroom.wordpress.com/ Definitions 7. P r o g r a m d a t a t yp e s : Definition Examples A positive or negative whole number be used in 150 mathematical operations -100 Data type Integer A positive or negative number that has a Real 100.5 fractional part that can be used in mathematical -15.2 operations Char A single character from the keyboard String A sequence of characters Boolean Data with two possible values H Hello World A312_@odq TRUE/FALSE 8. S e q u e n t i a l s t a t eme n t s Definition: Statements are executed one after another according to their order. 9. Conditional/Selection st ate ment s Definition: Selective statement(s) are executed depending on meeting certain criteria. Purpose: To allow different paths through a program depending on meeting certain criteria. 10. IF .. THEN .. ELSE .. ENDIF Definition: A conditional structure with different outcomes for true and false. Purpose: It allows for checking complex conditions. 101 http://britishstudentroom.wordpress.com/ Definitions 11. CASE .. OF .. OTHERWISE .. ENDCASE Definition: A conditional structure that allows selection to be made based on value of a variable. Purpose: Used to test for a large number of discrete values. 12 . Itera tive/Re pet ition s t a t e me n t s Definition: One or more statements are repeated till a test condition is met or whilst a test condition is TRUE. Purpose: To repeat same or similar code a number of times, which allows for shorter code. 13. FOR .. TO .. NEXT Definition: A loop structure that iterates a set number of times. 14. WHILE .. DO .. ENDWHILE Definition: A loop that iterates whilst a specified condition exists Criteria is pre-tested (It has criteria check at the start) It may never run 15. REPEAT .. UNTIL Definition: A loop that iterates until a condition is met Criteria is post-tested (It has criteria check at the end) It iterates at least once Differences between REPEAT ... UNTIL and WHILE ... DO ... ENDWHILE: In WHILE the criteria is pre-tested but in REPEAT..UNTIL the criteria is post-tested WHILE may never run while REPEAT.. UNTIL runs at least once WHILE iterates whilst a condition is TRUE but REPEAT UNTIL iterates till a condition is TRUE 102 http://britishstudentroom.wordpress.com/ Definitions 16. Totaling Definition: The process of summing a list of number. Example: Sum Sum + Num 17. Counting Definition: The process of finding how many items are in a list. Example: Count Count + 1 18. Array Definition: A data structure that holds a number of elements of the same data type Purpose: To store multiple values under the same identifier making the code shorter Allows for simpler programming 19. Top-Down design Definition: The breaking down of a computer system into set of sub systems and then breaking each subsystem into set of smaller ones until each sub system performs a single action. 18. Structure C h a r t Definition: Diagram that shows the design of a computer system in a hierarchal way, with each level giving a more detailed breakdown of the system. 103 http://britishstudentroom.wordpress.com/ Definitions 19. Library routine Definition: It is a list of programming instructions that is: Given a name Already available for use Pre-tested Advantages of using library routines: Library routines make writing programs easier and faster as the code is already written They make testing the program easier as the code has already been tested and d eb u gged 20. Subroutine Definition: Set of programming statements for a given task and given a name Subroutine is written in High Level Language Can be procedure or function. 21. Function Definition: A subroutine that always returns a value. 22. Procedure Definition: A subroutine that doesn’t return a value. 23. Databas e Definition: A structured collection of related data that allows people to extract information in a way that meets their needs. 104 http://britishstudentroom.wordpress.com/ Definitions 2 4 . D a t a b a s e t e r ms : Term Definition Examples Table/File A collection of related records Table of students For a student the fields could include: Student name Student ID Age Address Gender Field A column that contains one specific piece of Field Name Title given to each field Record A row within a table that contains data about a Details (all information) of single item, person or event one student Primary Key/ A field that contains unique data and can’t be Key Field repeated for more than one once information and has one data type Student ID field 105 http://britishstudentroom.wordpress.com/ Definitions 25. Validation Definition: The automated checking by a program that data to be entered is sensible. 26. Examples of validation checks: Validation check Type Check Definition Examples Checks that the data entered has the A person’s age should be appropriate data type a number not text. An email address must be Presence Checks that some data has been entered Check and the value has not been left blank Range Check It checks that only numbers within a Exam marks between 0 specified range are accepted and 100 inclusive Length Check It checks that data contains an exact A password with exactly 8 number of characters characters in length Character It checks that a string of characters does not A name would not contain Check contain any invalid characters or symbols characters such as % given for an online transaction A company with IDs that Format Check It checks that the characters entered start with MS then three conform to a pre-defined pattern numbers would have a format of MS### Check Digit A digit that it is calculated from all the other digits and appended to the number Used in barcodes 106 http://britishstudentroom.wordpress.com/ Definitions 26. Verification Definition: Checking that the data has not changed during input to a computer or during transfer between computers. Purpose: To ensure the accuracy of transcription. Types: Screen/Visual Check Double Data Entry 27. Screen/Visual Check Definition: Data is compared visually with the source document by a user The user is asked to confirm that the data entered is same as original If user finds a difference, the data is re-entered 28. Double Data Entry Definition: Data is entered twice (sometimes by two different people) A computer checks that both entries are equal If they are not equal, an error message requesting to re-enter the data is displayed 107 http://britishstudentroom.wordpress.com/ Definitions 29 . T e s t i n g d a t a Definition: Data used to check that a computer program responds correctly to correct and incorrect data. 30. T yp e s of test data: Type Definition Examples Normal Correct data that should be accepted The month can be any whole Data number in the range of 1 to 12 All the following values are not allowed as inputs for the month: Data outside the limits of acceptability, Abnormal or wrong type of data, and should be Data r ej ected Negative numbers Any value greater than 12 Letters or non-numeric data Non-integer values (e.g., 3.5,10.75, etc.) Extreme Data at the limits of acceptability and it The extreme values of month can shoul d b e accept ed be either 1 or 12 Data Boundary Rejected Data The rejected data on the boundaries Boundary rejected values of month can be either 0 or 13 108 9 http://britishstudentroom.wordpress.com/ http://britishstudentroom.wordpress.com/ Theory Questions Theory Questions 1 109 http://britishstudentroom.wordpress.com/ 2 Theory Questions 3 110 http://britishstudentroom.wordpress.com/ Theory Questions 4 5 6 111 http://britishstudentroom.wordpress.com/ Theory Questions 7 112 http://britishstudentroom.wordpress.com/ Theory Questions 8 9 10 11 113 http://britishstudentroom.wordpress.com/ Theory Questions 12 114 http://britishstudentroom.wordpress.com/ Theory Questions 13 115 http://britishstudentroom.wordpress.com/ Theory Questions 14 15 116 http://britishstudentroom.wordpress.com/ Theory Questions 16 17 117 http://britishstudentroom.wordpress.com/ 18 Theory Questions 19 118 http://britishstudentroom.wordpress.com/ Theory Questions 20 21 119 http://britishstudentroom.wordpress.com/ Theory Questions 22 120