Download presentation
Presentation is loading. Please wait.
1
Software Design & Development
3 theory lessons of notes on web pages Development Methodologies, Analysis, Design, Implementation, Testing & Evaluation
2
Contents The Software Development Process Analysis
Questions Analysis Design Notations – Structure Diagrams Design Notations – Flow Charts Design Notations – Pseudocode User Interface Designs Variables & Data Types Assignments & Arithmetic operators Contents page with links to lesson topics
3
Standard Algorithms – Iterating an Array & Running Totals
Selection Questions Fixed Loops Standard Algorithms – Iterating an Array & Running Totals Conditional Loops Standard Algorithms – Input Validation Predefined Functions Errors & Bugs Testing & Documentation Evaluation
4
Software Development Process
The software development process is a six step process that programmers usually follow when creating software. The process is sometimes referred to as the waterfall model – as once you have completed one step, you move onto the next The steps are Analysis Design Implementation Testing Documentation Evaluation
5
Iteration The basic waterfall model is simplistic. In practice, iteration is used to improve the quality of the created software In iterative software development, earlier phases of the development process can be redone based on what has been learned later. In other words, you can go back up the waterfall! Analysis Design Implementation Testing Documentation Evaluation
6
Analysis The Analysis stage is where you identify the functional requirements of a program – what it has to do. At National 5 level, your analysis will work to identify how to solve a problem statement or brief. You will need to identify the: Inputs – What information will be entered into the program? Process – What will be done with the inputted information? Outputs – What information will the program display for the user?
7
Design In the design stage, the identified functional requirements are used to plan out how to create the software, and how it will do the tasks required of it. Different design notations will be used to create different parts of the design: The user interface can be designed using wireframing The program can be designed using pseudocode, structure diagrams or flowcharts While the functional requirements state what the software has to do, the design documentation will state how it does it
8
Implementation In the implementation stage, the software is created. To implement a program, you will have to identify which programming constructs are required for each part of the design. At National 5 level, the programs created should match the design as exactly as possible. Failing to match the design will result in lost marks in the coursework task.
9
Testing In the testing stage, the software is tested to make sure it is working correctly. To test a program successfully, a suitable set of test data that includes normal, extreme and exceptional test data should be used. When testing shows errors exist in the program, the programmer will usually return to one of the earlier stages in the development process to fix them. It is common to iterate through the development process many times to get a working program
10
Documentation Once software is “complete”, it can be documented. A number of different documents might be created The user guide or manual tells the user how to complete certain tasks with the software. The user guide is written for typical users and does not require significant computer expertise to understand Technical documentation covers technical information about the software, such as configuration, system requirements and application programming interface (API) documents for the software Technical documents are written for expert users and other programmers so they can modify the software
11
Evaluation In the evaluation stage, the software is judged in terms of how good it is. The most important consideration is whether or not the software is fit for purpose – does it do what it is supposed to, as set out in the functional requirements? There are a number of factors that should be considered as well Efficient use of coding constructs – does it complete it’s task in the minimum number of lines of code? Robustness – can the software handle errors without crashing? Readability – is the program code easy to read, using meaningful variable and subprogram names, and internal commentary?
12
Questions – The software Development Process
Answer questions in full sentences! List and briefly describe the six steps of the software development process. Explain how making the development process iterative can improve the quality of software produced. What needs to be identified to create the functional requirements of a program? What is meant by the term “fit for purpose” when testing and evaluating software. Why is this the most important consideration when evaluating software? List and describe other factors to consider when evaluating software. Describe two types of documentation that can be produced during the documentation stage.
13
Analysis In the Analysis stage of software development you will identify the functional requirements of the program to be made. The functional requirements identified define the program’s specification. This will be used in the evaluation stage to identify if the program has been created correctly. In commercial and industrial situations, the functional requirements and specification are very important – They will be used to judge how the software developers are paid for their work.
14
Problem Statements At National 5 level, analysis will be carried out on problem statements. A problem statement is a short description of a situation or problem to be solved. You have to think about what needs to be done to create a computer program that till resolve the situation Here is an example problem statement: A small class of students is studying a language course. They pass the course by passing the French test and by passing either the Spanish test or the German test. Each test is out of 20 and is passed with 10 or more marks. Write a program that will say if each student passes or fails.
15
Inputs The inputs of a program are the items of data that the user will have to enter in order for the program to provide the desired results. At National 5 level, you have to identify the inputs of a program. To work this out, think about what information you will need to know to solve the problem. In the example, we can only work out the passes and fails if we know what mark each student got for French, Spanish & German Inputs: French mark for each student. Spanish mark for each student. German mark for each student.
16
Process The processes of a program are the operations it carries out on data it has. A program will usually process the inputs along with any other information it has to work out the outputs. At National 5 level you have to identify the processes of a program. Examine the problem statement carefully to identify what the program has to do. In the example, we know we have to work out who passes the course, but by reading the statement carefully we can describe how we work this out. Processes: Work out if each student passes French. Work out if each student passes Spanish. Work out if each student passes German. Work out if each student passes the whole course.
17
Outputs The outputs of a program are the results that the program will display. At National 5 level you have to identify the outputs of a program. Usually the problem statement will make these very obvious, but sometimes you will have to think about what the outputs are based on the processes completed. In the example, it is very clear that we have to state whether or not the students have passed the course. Outputs: Whether each student has passed or failed the language course.
18
Assumptions An assumption is a decision that you have made about the program design, but which is not based on the problem statement. Not every program requires assumptions to be made, but sometimes you need to make an assumption in order to use some of the software constructs you will learn about to complete the program. In the example, the problem statement says nothing about the size of the class except that it is “small”. To use arrays and loops in this program we need to know how many students there are. We will make an assumption so we are able to use arrays and loops. Assumptions: There are five students in the class.
19
Analysis Example – Language Course
The problem: A small class of students is studying a language course. They pass the course by passing the French test and by passing either the Spanish test or the German test. Each test is out of 20 and is passed with 10 or more marks. Write a program that will say if each student passes or fails. The analysis: Inputs: French mark for each student. Spanish mark for each student. German mark for each student. Processes: Work out if each student passes French. Work out if each student passes Spanish. Work out if each student passes German. Work out if each student passes the whole course. Outputs: Whether each student has passed or failed the language course. Assumptions: There are five students in the class. This is not the only valid analysis of this problem! Other solutions are possible.
20
Questions – Analysis Answer questions in full sentences!
What is an assumption? Why do assumptions have to be made sometimes in the analysis stage? For each of the following problem statements, identify the inputs, processes and outputs of the program to solve them. A factory worker is paid based on the number of widgits they make. They get paid the same amount for each widget. Calculate and display the workers wage. A group of triplets – Alice, Bob & Carol – are taking a maths test. Their mother has promised to take them to an amusement park if their average score is more than Write a program that says if they get to go or not . Three people have just measured their heights. Write a program that will print the name of the tallest person. “Software Development for Beginners” costs £ If you buy more than 10 copies you get a 10% discount. Write a program to calculate the cost of your order.
21
Design Notations – Structure Diagrams
After you have identified the inputs, processes and outputs you are ready to create the design for the program. The design of a program sets out how the program will solve the problem that has been set. The design will be used to create the program code. At National 5 level you must make programs match their design, even if you think you could do better. Structure diagrams are a type of design notation. They show the steps taken by the program. A structure diagram is read from top to bottom, then left to right. Calculate sum of 2 numbers A very simple structure diagram Input numbers Calculate sum Display sum
22
Structure Diagram Symbols
Structure diagrams use different shapes to represent different things that can happen in a program: Operation An operation such as a calculation, or getting input or printing something out. Loop The program will repeat the blocks below. This may be a set number of times or until a condition is met. Selection The program will chose one of the blocks below to follow depending on a condition. Pre-defined An operation that uses a built in or pre-defined function of a programming language. It does not need to be described any further.
23
Design Example – Language Course
We previously analysed the following problem The problem: A small class of students is studying a language course. They pass the course by passing the French test and by passing either the Spanish test or the German test. Each test is out of 20 and is passed with 10 or more marks. Write a program that will say if each student passes or fails. The analysis: Inputs: French mark for each student. Spanish mark for each student. German mark for each student. Processes: Work out if each student passes French. Work out if each student passes Spanish. Work out if each student passes German. Work out if each student passes the whole course. Outputs: Whether each student has passed or failed the language course. Assumptions: There are five students in the class.
24
Language Course Design – 1st Attempt
When creating a design, you should start with a structure based on input, process and output. For our example program this will be: However, this design is lacking in detail and needs to be redrafted. Program Name Input Processes Output Language Courses Get all the marks Calculate results Display results
25
Language Course Design –2nd Attempt
We should explain the inputs, process and outputs in more detail. We should also consider how any assumptions we make affect the design. This gives us something like: Language Courses Loop 5 times Loop 5 times Loop 5 times Display result Get French mark Get Spanish mark Is French mark >= 10 No Get German mark Yes Set result to Fail Is German mark >= 10 or is Spanish mark >= 10 No Yes This plan has sufficient detail. It could be made more efficient, which we will look at later. Set result to Fail Set result to Pass
26
Questions – Structure Diagrams
Using the following problem descriptions and analysis, create structure diagram designs. Problem Dave, Elise and Frank are collecting money for charity. They have counted up how much they each collected. Design a program to display the total money collected. Analysis Inputs: Dave’s collection, Elise’s Collection, Frank’s collection Process: Add up the total Outputs: Display the total collected
27
Problem Jane is buying cakes for a party. Each person at the party will get a cake. The cake shop will give Jane a 10% discount if she has a voucher. Design a program to display the cost of the cakes Analysis Inputs: How many people coming to party Cost of each cake If Jane has a voucher Process: Calculate cost of cakes Apply discount if Jane has a voucher Outputs: Display the total cost Assumptions: Each cake costs the same
28
Problem A class has just finished their maths test. 40 marks or more is a pass. Design a program to display how many pupils passed. Analysis Inputs: Each pupil’s mark Process: Check if each mark is over 40. Add one to number of passes if it is Outputs: Display the number of passes Assumptions: There are 20 pupils in the class
29
Examine the following problem statement and structure diagram
Examine the following problem statement and structure diagram. Identify the error in the program. Draw a corrected structure diagram. Problem A car salesperson gets paid a bonus depending on how many cars she sells. If she sells more than 5 his bonus is £200. If she sells 10 or more, the bonus is increased to £500. Sales bonus Get cars sold Is cars sold >= 5 Is cars sold >= 10 Yes Yes Display bonus is £200 Display bonus is £500
30
Design Notations - Flowcharts
In addition to structure diagrams, you also need to be able to read and create program designs using flowcharts. A flowchart is a design notation that shows the order a program is executed in. To read a flow chart, follow the arrows from the start to the end, making decisions where required. Flowcharts are very good for dry-running a program: Checking how a program will work if you execute it. They also bear more resemblance to the finished program code than structure diagrams. Start Set height initially 0 Set width initially 0 Input height Input width Set area to height * width Display area End A simple flowchart
31
Flowchart Symbols Flowcharts use different shapes to represent different things that can happen in a program: Flow line Show the direction or flow between symbols. Terminal Indicates the start and end of a flowchart. Operation An operation such as a calculation. Can sometimes be several operations combined into one block. Input / Output Shows where the user has to enter data, or when it will be printed out on the screen.
32
Decision The flowchart may branch depending on the conditions described. Can ask a question, follow the flow line that answers the question. Can include a condition. Evaluate the condition to true or false and follow the appropriate flow line. Predefined An operation that uses a built in or pre- defined function of a programming language. Connector May be used to split a flowchart into sections, so it can be kept on one page. Initialisation Set the starting value of a variable. No Yes
33
Design Example – Guess Number
We are going to consider the flowchart for the following problem The problem: A number guessing game is played: The player has to guess the number on the computer, which is randomly generated. Each guess, the player is told if the computers number is higher or lower. The game continues until the user gets the number. They are told how many guesses they took The analysis: Inputs: The users guess. Processes: Generate a random number. Keep track of the number of guesses. Work out if the number is higher or lower than the guess. Outputs: If the number is higher/lower. The number of guesses taken.
34
Guess Number Design – 1st Attempt
When creating a design, you should start with a structure based on input, process and output. However, sometimes a process or output needs to happen before input: As before, this design is lacking in detail and needs to be redrafted. Start Start Input Generate number Display Feedback For our example program, this will be: Number Guessed? Process Input Guess No Output Track guesses and work out feedback Yes Display no of guesses End End
35
Guess Number Design –2nd Attempt
We should explain the inputs, process and outputs in more detail. We should also consider how any assumptions we make affect the design. This gives us something like: Start Generate number Yes Number < Guess Set no of guesses initially 0 Display “Lower” No Input Guess The plan now has sufficient detail. It could be made more efficient, which we will look at later. Number Guessed? Add 1 to no of guesses No Yes Yes Number > Guess Display no of guesses No Display “Higher” End
36
Questions – Flow Chart Using the following problem descriptions and analysis, create flow chart designs. Problem Write a program to calculate the perimeter of a rectangle. Analysis Inputs: Length of rectangle. Height of rectangle. Process: Calculate the perimeter. Outputs: Display the perimeter of the rectangle.
37
Problem A team of three skaters is taking part in a competition. They go through to the next round if their average score in the first round is more than 4. Write a program to work out if they go through or not Analysis Inputs: Skater 1 score. Skater 2 score. Skater 3 score. Process: Calculate average score. Work out if they go through or not. Outputs: if they go through or not.
38
Problem A company only rents out vans to people who are at least people come into the office one day and want to rent vans. Write a program that will say if they are allowed to rent vans or not. Your program should be efficient – looping round 5 times. Analysis Inputs: Each person’s age. Process: Check if person is 25 or more. Check if you have asked for 5 peoples ages yet. Outputs: Display if each person can rent a van.
39
Password includes a symbol
Examine the following problem statement and flow chart. Identify the error in the program. Draw a corrected flow chart. Problem A user is asked to create a password. It must include a symbol and be at least 8 characters long. If it does note meet these criteria, the user is asked to enter again until it does. Start Input new password No Password includes a symbol Password length >=8 No Yes Yes End
40
Design Notations - Pseudocode
Pseudocode is a design notation that sets out what an algorithm will do. It uses the structure of a programming language, but uses English words instead of program code. This pseudocode example shows the algorithm for calculating the area of a square: 1) Input length 2) Calculate area = length times length 3) Display length Because the words are similar to English, it is easier to understand what the program does. Pseudocode is easy to translate into a programming language – each line of pseudocode should be equivalent to a line of code in the programming language The equivalent python code
41
SQA Reference Language
The National 5 Computing Science exam will use questions with the SQA Reference Language in them. It is not a pseudocode, but can be used in the same way as one. You will be expected to Explain what sections of pseudocode or the reference language do Identify and correct errors in pseudocode or the reference language Write small sections of pseudocode These notes will make use of the reference language in place of pseudocode. You will learn it as we cover more programming constructs. You must be able to understand the reference language, but you do not need to use it when creating pseudocode yourself.
42
Reference Language vs Pseudocode
Calculating the perimeter of a rectangle in SQA reference language. 1) RECEIVE length FROM KEYBOARD 2) RECEIVE width FROM KEYBOARD 3) SET perimeter TO 2 * length + 2 * width 4) SEND perimeter TO DISPLAY Calculating the perimeter of a rectangle in an informal pseudocode. 1) Get user to enter length. 2) Get user to enter width. 3) Calculate perimeter: 2 times length + 2 times width. 4) Print out the perimeter. Either of these is acceptable when an exam question asks you to write code or pseudocode!
43
Design Example – Salary Raise
We are going to consider the flowchart for the following problem: The problem: 4 workers are getting a raise in their pay. Each worker will get the same percentage raise, though their current salaries are all different. Write a program to display their new pay. The analysis: Inputs: The percentage increase. Each of the workers new pay. Processes: Calculate each worker’s new salary. Outputs: Each worker’s new salary.
44
Salary Raise Design – 1st Attempt
When creating a design, you should start with a structure based on input, process and output. 1) Get raise percentage 2) Get each salary 3) Calculate new salaries 4) Display new salaries We know that this design is lacking in detail as each line of pseudocode does not equate to one line of program code. It needs to be redrafted. Inputs Process Output
45
Salary Raise Design – 2nd Attempt
In reference language: 1) RECEIVE raisePercent FROM KEYBOARD 2) REPEAT 5 TIMES 3) RECEIVE salary FROM KEYBOARD 4) END REPEAT 5) REPEAT 5 TIMES 6) SET salary TO salary * (1 + raisePercent/100) 7) END REPEAT 8) REPEAT 5 TIMES 9) SEND salary TO DISPLAY 10) END REPEAT In pseudocode: 1) Get user to enter the raise percentage. 2) Loop 5 times. 3) Get user to enter a salary. 4) End of loop. 5) Loop 5 times. 6) New salary is salary + raise percentage percent. 7) End of loop. 8) Loop 5 times. 9) Print out new salary. 10) End of loop. The plan now has sufficient detail. It could be made more efficient, which we will look at later.
46
Questions - Pseudocode
Answer questions in full sentences! Write a short description of what a program with the following pseudocode does: 1) Input radius. 2) Calculate area using a = π r2. 3) Display the area of circle. 1) Input the test mark. 2) if the mark is more than or equal to 10: 3) Tell the user that they have passed. 4) otherwise: 5) Tell the user that they have failed. 6) end of if.
47
Using the following problem descriptions and analysis, create pseudocode designs.
Write a program to ask the user how old they are and then tell them if they are allowed to learn to drive. You must be at least 17 to learn to drive. Analysis Inputs: Age. Process: Work out if allowed to drive. Outputs: If allowed to drive or not. A maths test is made up of five simple addition sums. Each sum is worked out by adding two numbers. Write a program to calculate the answer to each of the 5 questions. Inputs: Five sets of two numbers each. Process: Add each set of two numbers together. Outputs: Five answers to the questions.
48
Examine the following problem statement and pseudocode
Examine the following problem statement and pseudocode. Identify the error in the program. Write down corrected pseudocode. Problem A user has to enter a password to access their account. They get three attempts. If they enter the correct password they gain access immediately. If they fail three times, access is blocked 1) Number of attempts = 0. 2) Repeat: 3) Input password. 4) Add 1 to number of attempts. 5) Until number of attempts = 3. 6) If password is correct: 7) Give access. 8) Otherwise: 9) Block access. 10) End of if.
49
User Interface Designs
The user interface is the part of a computer program that is visible to the user. The user interface will include places to enter the input of the program. It will also have some space to display the output of the program. In National 5 Computing Science, there are two type of program user interfaces: Text based user interfaces and graphical user interfaces.
50
Graphical User Interfaces
Development environments like Visual Basic use graphical user interfaces in the programs created. The user interface design must include spaces for the user to type in input. There must be a space, or spaces for output to appear. There will usually also be one or more buttons that the user has to click on to make the program run.
51
Graphical User Interface Design
Calculator Program Number 1 Number2 Answer + - = * / A graphical user interface design. This program can be used to add, subtract, multiply or divide two numbers. It shows the space allocated for: Buttons to make the program execute. Labels to display instruction text to the user. Textboxes for input and output.
52
Text Based User Interfaces
The Python programs you create will make use of text based user interfaces. Text based user interfaces consist of a series of lines of prompts printed out by the program one after the other. If a prompt requires input from the user, the program will pause until the user has typed in their response and hit the enter key. You should chose the text for prompts carefully, so the user knows exactly what they have to type in.
53
Text Based User Interface Design
A text based user interface design. This program works out if a number of pupils pass or fail their language course. It includes: Prompts to the user and displayed text. Sample user input to illustrate program executing. Annotations to explain what is happening. Note that it does not show all of the text displayed by the program.
54
Questions – User Interface Design
Create a graphical user interface design and a text user interface design for each of the following sets of input, process and output: Inputs: Length of rectangle. Height of rectangle. Process: Calculate the area. Outputs: Display the area of the rectangle. Inputs: Candidate’s Name. Candidate’s mark in session 1. Candidate’s mark in session 2. Process: Check if combined mark is greater than 50. Outputs: Display the candidates name and if they have been accepted to the Conservatoire.
55
Inputs: The names of five people.
The distance they travel to work. Process: Check if they live more 20 miles away – if so they get travelling expenses. Outputs: Display the names and whether they get expenses paid or not. Inputs: Guessing a number between 0 and 20 until it is guessed correctly. Process: Check if the guess is correct, or higher or lower than the target number. Keep track of the number of guesses made Outputs: Display if the guess is higher or lower than the target number. Display the number of guess made once the number had been guessed correctly.
56
Variables In a computer program, a variable is part of the computers memory that has been set aside to store a single item of information for the program. The program can use the information stored in the variable to carry out calculations and display output. 4
57
Variables should have meaningful names which tell you about what the information stored in them represents. Variables should also have data types which say how the computer is storing the information, and how it can be used in your program. When you change the value inside a variable, the old value is lost forever. 14 Store 16 in age variable 16 or age integer Store 16 in age variable age integer or SET age TO 16
58
Data Types Boolean variables have one of two values – either True or False. The user can’t enter Boolean values as input easily in Python. Strings are made up letters, symbols and numeric characters. To ask the user to enter a string in python: name = input(“Enter your name: ”)
59
Integers are whole numbers.
To ask the user to enter a integer in python: age = int(input(“Enter your age: ”)) Floating point or real numbers can have any value – whole numbers and the fractions in- between. To ask the user to enter a floating point in python: height = float(input(“Enter your height: ”))
60
Arrays An array is a special type of data structure that can hold multiple values, using an index to identify each value. Most programming languages make index [0] the first element in an array. Arrays can be of any of the data types – an array of integers would hold multiple whole number values. For example: 14 17 12 7 age[0] integer[] age[1] integer[] age[2] integer[] age[3] integer[]
61
Questions – Variables and Data Types
Answer questions in full sentences! Describe the four data types and what kind of information they can store. Explain the difference between a variable and an array. Copy and complete the following table, choosing an appropriate variable name and data type for each variable. Variable Name Data Type Description deskLength Floating point The length of desk in metres age Integer array A list of peoples ages The number of pupils in a class The name of a ship Your height in metres The number of subjects you take A car registration number
62
Variable Name Data Type Description The average test mark of a class The register of pupil names for a class A list of rainfalls for the month measured in mm A list of fractions A collection of judge scores in a dancing competitions for one competitor
63
Assignments An assignment is when a value is stored in a variable.
The value stored can either be a literal value, the contents of another variable or the result of a calculation. The SET keyword is used to indicate assignments in the reference language. Process boxes are used in flow charts and structure diagrams. SET weight TO 70 a literal value SET weight TO newWeight another variable SET weight to oldWeight + change a calculation Store 70 in weight variable Store 70 in weight variable Store newWeight in weight variable Store newWeight in weight variable Add oldWeight + change, store them in weight variable Add oldWeight + change, store them in weight variable
64
You can also assign values to the individual elements of an array
You can also assign values to the individual elements of an array. You must identify which element to assign to by including its index SET weight[4] TO oldweight[4] + change Different elements can be changed by using different indices You can even use a integer type variable as an array index: SET profit[day] TO number sold[day] * profitMargin
65
Arithmetic Operators When the variable you are assigning to is of a numeric type like integers and floating points, you can carry out a calculation before assigning the result to the variable. The arithmetic operators allow you to carry out these calculation by adding, subtracting, multiplying and dividing values and values stored in variables.
66
+ Use + to add two values or variables together, for example: SET total TO bookCost + posterCost - Use - to subtract one value or variable from another, for example: SET moneyLeft TO 20 - bookCost * Use * to multiply two values or variables together, for example: SET total TO posterCost * numberBought
67
/ Use / to divide one value or variable by another, for example: SET averageCost TO totalCost / number bought ^ Use ^ to raise one value or variable to the power of another, for example: SET cubeVolume TO cubeLength ^ 3
68
Operator Precedence The arithmetic operators have an order of precedence. Multiplying and dividing will happen before addition and subtraction. If you want to add or subtract first, you must enclose that part of the calculation inside brackets. Not using brackets when necessary is a common cause of logic errors! SET average TO num1 + num2 + num3 / 3 SET average TO (num1 + num2 + num3) / 3
69
String Concatenation When the variable you are assigning to is of a string type, the arithmetic operators can not be used. Instead, multiple strings or parts of strings can be joined together. This is called string concatenation. SET fullname TO firstname + “ ” + lastname Other operations can be applied to strings, but you do not need to know about them at N5 level.
70
Questions – Assignments
Answer questions in full sentences! What is an assignment? List the arithmetic operators – state what each one does. Write a line of pseudocode for each of the following assignments: Store the value “Alice” in a variable called name. Calculate the totalSales for a concert using the variables costPerTicket and numberOfTicketsSold. Using the variable radius, calculate the area of a circle. The area of a circle is the radius squared multiplied by π.
71
Identify and correct the errors in the following structure diagrams:
A program to calculate the cost of buying juice and crisps for every pupil in a class. A program to calculate the average of 3 numbers. Snack Costs Get cost of 1 juice Get cost of 1 crisps Get no of pupils Total cost = juice cost + crisp cost * no of pupils Display total cost Average Enter Num 1 Enter Num 2 Enter Num 3 Calculate average to (Num 1+ Num 2 +Num3) / 2 Display average
72
Selection Selection allows a program to process information in different ways. When using selection, a condition is evaluated to see if it is either True or False. The program will execute lines of code depending on how the condition is evaluated. In reference language: IF condition THEN … ELSE END IF Any code in here executes if the condition is True. Any code in here executes if the condition is False. The ELSE part of the IF statement, and the code it executes do not need to be included.
73
IF Statement Programming languages implement selection using the IF statement. This example of reference language shows a program that applies a 10% discount to the cost of books if more than 100 are bought. IF numberBought > 100 THEN totalCost = costPerBook * numberBought * 0.9 ELSE totalCost = costPerBook * numberBought END IF Python doesn’t use and END IF line, instead indentation is used to indicate what code is inside the if statement.
74
Selection Flowcharts & Structure Diagrams
The same 10% discount program as a flow chart and structure diagram would look like this: More than100 books? Yes Were more than 100 books ordered? The total cost is 90% of the number bought * cost per book No Yes No The total cost is the number bought * cost per book The total cost is 90% of the number bought * cost per book The total cost is the number bought * cost per book
75
ELSE IF ELSE IF allows multiple if statements to be chained together. An ELSE IF condition is only evaluated if the previous condition was False. Using ELSE IF makes a program more efficient as it reduces the number of conditions that have to be evaluated. Python uses the elif command for ELSE IF. IF condition 1 THEN … ELSE IF condition 2 THEN ELSE END IF condition 2 is only checked if condition 1 is False. Any code here is executed if condition1 is false but condition 2 is True. Any code in here executes both conditions are False. ELSE IF and ELSE are both optional. They don’t need to be included.
76
ELSE IF In Flowcharts & Structure Diagrams
ELSE IF in flow charts and structure diagrams looks like this: Condition 1 Condition 1 False True False True Condition 2 … Condition 2 False True False True … … … … … Multiple ELSE IFs can be chained into a row. Each one is only evaluated if the previous condition was found to be False.
77
Conditions You will need to be able to create appropriate conditions for your programs. A simple condition compares two values using a comparison operator. The compared values can be either literal values, the contents of a variable or a calculation using the arithmetic operators. mark1 + mark2 >= 15 In the above condition, the values stored in the variables mark1 and mark2 are added together and compared to the value 15. If the sum of mark1 and mark2 comes to 15 or more, the condition is evaluated as being True, if the sum of mark1 and mark2 is less than 15, the condition is False.
78
Comparison Operators The comparison operators compare two values and return a result of either True or False. There are are six different ways the values can be compared. Pseudocode Comparison Python = True if the values on both sides of the operator are exactly the same. == ≠ True if the values on both sides of the operator are different. != > True if the value on the left side of the operator is more than the value on the right . < True if the value on the left side of the operator is less than the value on the right . ≥ True if the value on the left side of the operator is the same as or more than the value on the right . >= ≤ True if the value on the left side of the operator is the same as or less than the value on the right . <=
79
Complex Conditions A simple condition compares two values using a comparison operator. More complex conditions can be created using multiple simple conditions. A complex condition usually consists of two or more simple conditions that are joined together using logical operators. The logical operators describe how the results of the simple conditions should be evaluated together. Like simple conditions, complex conditions will evaluate to a result of either True or False .
80
Logical operators There are three logical operators: AND, OR and NOT
Pseudocode How it evaluates Python AND If both of the simple conditions connected by AND are True, the whole condition is True. If only one is True, or if both are False, the whole condition is False. and OR If either one of the simple conditions connected by OR is True, the whole condition is True. It is also True if both simple conditions are True The whole condition only evaluates to False if both simple conditions are False. or NOT NOT only uses one simple condition, which appears on its right. NOT inverts the value of the condition to its right: True becomes False and False becomes True. not
81
Questions – Selection Answer questions in full sentences!
Evaluate the following conditions, stating whether they are True or False. You may assume the variables age, height and name contain the following values: name ≠ “Alice” height > 1.50 age > 14 age ≥ 14 NOT name = “Bob” age = 14 AND height ≤ 1.90 age + 4 < 18 Name = “Alice” OR name = “Bob” 14 1.87 Alice age height name
82
Answer questions in full sentences!
Write down the value in the variable speed after each selection construct has executed. SET acceleration TO 5 SET speed TO 10 IF acceleration < 5 THEN SET speed TO speed + acceleration ELSE SET speed TO speed – acceleration END IF . Start Acceleration = “go” False acceleration = “Go” True speed= “Slower” Speed = “Fast” speed= “Faster” End
83
IF acceleration ≥1 AND NOT acceleration < 5 THEN
. SET acceleration TO 5 SET speed TO 10 IF acceleration ≥1 AND NOT acceleration < 5 THEN SET speed TO speed + acceleration ELSE SET speed TO speed – acceleration END IF Speed Program Store 5in acceleration Store 10 in speed Acceleration <=5 and speed > 5 No Yes Store speed + acceleration in speed Store speed – acceleration in speed
84
Answer questions in full sentences!
Identify and correct the error in the following sections of pseudocode: A program that tells you turn on the heating if the temperature is less than 10oC: 1) IF temperature ≤ 10 THEN 2) SEND “Turn heating on” TO DISPLAY 3) END IF A program that displays an error message when the user fails to enter a valid menu number choice between 1 & 3: 1) IF choice ≥ 1 AND choice ≤ 3 THEN 2) SEND error message TO DISPLAY Create a flowchart for a program that tells users which grade they compete in based on their age. People older than 18 are in the silver grade, 15 to 18 year olds are in the sour grade and younger than 15 is the triangle grade.
85
Iteration & Fixed Loops
In iteration a line of code, or several lines of code, is executed many times. Iteration means programs can be efficient – we only need to write one line of code, but the effect will happen many times. It also reduces the risk of creating an error or bug, which becomes more likely if we have to type the line in several times. A fixed loop is a type of programming construct used for iteration. Fixed loops happen a set number of times. If a fixed loop is programmed to happen six times, it will always happen exactly six times. If it programmed to happen noOfTimes times, it will happen a number of times equal to the value stored in the variable noOfTimes .
86
The FOR loop The FOR loop is an example of a fixed loop. A FOR loop states a start and end value for repetition. This example will display the same line ten times: FOR times FROM 1 TO 10 DO SEND “I must not talk in class” TO DISPLAY END FOR Outputs: … Note the lack of an END FOR line in Python. Additionally, the range specifies the last number you want to execute the loop with plus 1.
87
Loop Control Variables
FOR loops usually have a loop control variable. The loop control variable counts how many times the loop has been completed. The loop control variable can be used to make a FOR loop do something slightly different each time it executes. This example makes it show the six times table: FOR times FROM 1 TO 10 DO SEND “6 times” times “is” times * 6 TO DISPLAY END FOR Outputs: … The first time the loop executes, the value in times is 1, resulting in this line. The second time the loop executes, the value in times is 2, resulting in this line.
88
Iteration Flow Charts and Structure Diagrams
The same times table program in flow chart and structure diagrams would look like this: Start Loop 10 times Set times to 1 Display 6 times the number of times we’ve been through the loop is… Times = 11 True False Referring to the loop control variable in flow charts and structure diagrams is difficult. Structure diagrams do not mention loop control variables. Flow charts show fixed loops as conditional loops. Display 6 times the value in times is… Add 1 to times End
89
REPEAT … TIMES REPEAT … TIMES is an alternative method of writing a fixed loop in reference language instead of using a FOR loop. The REPEAT … TIMES loop works in the same way as the FOR loop, but it does not have a loop control variable. There is no equivalent to this loop in Python and you are only likely to see it in your exam paper. This example works exactly the same as the first FOR loop example – it displays a line ten times: REPEAT 10 TIMES SEND “I must not talk in class” TO DISPLAY END REPEAT
90
Questions – Fixed Loops
Answer questions in full sentences! Give two advantages of using loops to make something happen many times instead of repeating the same line of code? Write down the value in the variable speed after each fixed loop construct has executed SET speed TO 2 FOR counter FROM 1 TO 3 DO SET speed TO speed * speed END FOR . FOR Speed initially 4 Counter initially 1 True counter = 6 False Set speed to counter Add 1 to counter
91
Display the number of times the loop has executed * 2
Answer questions in full sentences! Identify and correct the error in the following designs A program that prints out the first ten numbers squared A program checks if 3 users have remembered to put their clocks back and reminds them to do it if they have not 1) FOR i FROM 1 TO 4 DO 2) SEND “Did you remember to reset your clock?” TO DISPLAY 3) RECEIVE answer FROM KEYBOARD 4) IF answer=“No” 5) SEND “Better change it now” TO DISPLAY 6) END IF 4) END FOR EACH Write a structure diagram for a program that asks 5 users what their favourite school subject is. The program will print out the number of pupils that picked Computing. Loop 10 times Display the number of times the loop has executed * 2
92
Standard Algorithms – Running Total
Standard algorithms are simple generic algorithms that can be adapted and reused in your program. Two of the three standard algorithms you need to know at National 5 are running totals, iterating arrays and input validation. A running total is when a loop is used to add up a series of numbers inputted by the user. The total is updated each time a new number is entered. This example shows a running total of 10 scores: SET totalScore TO 0 REPEAT 10 TIMES RECEIVE nextScore FROM KEYBOARD SET totalScore TO totalScore + nextScore END REPEAT
93
Running Total Flow Charts and Structure Diagrams
The same running total program in flow chart and structure diagrams would look like this: Initialise total score to 0 Initialise times to 1 Initialise total score to 0 Repeat 10 times True i = 11 False Enter a new score Add the new score to the total score Enter next score Add next score to the total score Add 1 to times
94
Standard Algorithms – Iterating through an array
Iterating through an array is when the same thing is done to each index of an array. This can be getting input, carrying out some process or printing out the entire contents of the array. When iterating through an array, the loop control variable is used as the array index. This makes the process happen to each index in turn as the loop executes. This example shows getting input for all the indices in two arrays: FOR EACH pupil FROM pupilNames DO RECEIVE pupilNames[pupil] FROM KEYBOARD RECEIVE pupilMarks[pupil] FROM KEYBOARD END FOR EACH range(0,noOfPupils) means the loop executes noOfPupils times, starting at 0 and ending at noOfPupils - 1 This string concatenation means that the instructions to the user are slightly different each time, making the program more readable
95
Iterating An Array Flow Charts and Structure Diagrams
The same pupil and marks input program in flow chart and structure diagrams would look like this: Set pupil to 0 Repeat a number of times equal to the number of pupils True pupil = noOfPupils False Enter the name of a pupil, store it in the appropriate index Enter the markof a pupil, store it in the appropriate index Enter pupilNames [pupil] Enter pupilMarks [pupil] Add 1 to pupil
96
Questions – Running Totals & Iterating An Array
Answer questions in full sentences! Why is using a loop to iterate an array better than using multiple different variables? Write down the value in the variable speed after each fixed loop construct has executed. Use the input given. SET speed TO 10 FOR counter FROM 1 TO 3 DO RECEIVE acceleration FROM KEYBOARD SET speed TO speed + acceleration END FOR . D FOR Input: 4, -6, 3 True Set samples to [4, 7,6,2] counter = 4 False Set speed to 0 Set speed to speed + samples[counter] Set counter to 0 Add 1 to counter
97
Identify and correct the error in the following program designs
A program that prints out the contents of two arrays, owners and their dogs. A program that counts the number of rainy days in a week – a rainy day has more than 10mm rainfall. ) True i = 4 Owners initially is [Alice, Bob, Carol, Dave, Elise] False Display Pets[i] “is owned by” Owners[i] Pets initially is [Rover, Max, King, Fluffy, Butcher] Increment i i initially is 0 Rainfall is [0,5,17,12,4,8,25] Rainy days is 0 Loop 7 times Print out Rainy days If Rainfall[times through loop] > 10 Yes Add Rainfall[times through loop] to Rainy days
98
Write a structure diagram for a program keeps a running total of the number of strokes played by a golfer during a round of golf. Remember that there are 18 holes on a golf course. Write pseudocode for a program that inputs and stores the name, address and phone number of five lawyers.
99
Conditional Loops A conditional loop does not always happen a fixed number of times. Each time the loop is executed, a boolean condition similar to those used in the IF statement is evaluated. The program uses the evaluated result to decide whether or not to execute the loop again. The condition can be evaluated at the start or the end of the loop. If the condition is evaluated at the start of the loop, the loop may not need to be executed at all. Some types of loops will execute while the condition is True. Other types of loops will execute as long as the condition is False – they keep on going until the condition is True .
100
WHILE loop A WHILE loop is a conditional loop that evaluates its condition at the start of the loop. The body of the loop will execute as long as the condition is True . This example WHILE loop keeps executing until the user guesses the correct number. WHILE guess ≠ number DO RECEIVE guess FROM KEYBOARD END WHILE SEND well done message TO DISPLAY Outputs: … To make sure this loop happens at least once, we must set the default value of guess to something that is different from the value of number
101
While Loop Flow Charts and Structure Diagrams
The same guess number program in flow chart and structure diagrams would look like this: Initialise guess to 0 Number is a random Number between 1 & 10 Initialise guess to 0 Number is a random Number between 1 & 10 Repeat while guess ≠ number False guess ≠ number Enter a guess True Enter guess These diagrams show how variables can be initialised to ensure the loop runs at least once.
102
REPEAT UNTIL loop A REPEAT UNTIL loop is a conditional loop that evaluates its condition at the end of the loop. The body of the loop will execute as long as the condition is False . This example loop replicates the function of the previous WHILE loop. However, it will always execute at least once so we do not need be careful with the default values of guess and number: REPEAT RECEIVE guess FROM KEYBOARD UNTIL guess = number SEND well done message TO DISPLAY The REPEAT UNTIL loop does not exist in Python – instead you have to use the while loop. Make sure the values in your variables force the loop to execute at least once in this case!
103
Repeat Until Flow Charts and Structure Diagrams
The same guess number program in flow chart and structure diagrams would look like this: Initialise guess to 0 Number is a random Number between 1 & 10 Number is a random Number between 1 & 10 Repeat until guess = number Enter guess Enter a guess guess = number False True
104
Infinite Loops An infinite loop is an example of an execution error. The program becomes stuck in a conditional loop construct and is unable to leave it. This causes the program to appear to stop working, or ‘hang’. Infinite loops occur when you make a mistake that means the result of evaluating the loop condition is always the same, making it impossible to break the loop. This example shows a loop that will continue forever: SET speed TO 10 WHILE speed > 5 DO SET acceleration TO speed / 10 END WHILE When creating a conditional loop in your programs, the code inside the loop should always change the variables used in the condition in some way.
105
Questions – Conditional Loops
Answer questions in full sentences! Describe two differences between WHILE loops and REPEAT … UNTIL loops. Write down the value in the variable speed after each conditional loop construct has executed. SET speed TO 10 WHILE speed > 4 DO SET speed TO speed - 1 END WHILE . Initialise speed to 5 Repeat until speed ≥ 10 Add 3 to speed
106
Answer questions in full sentences!
Identify and correct the error in the following program designs: A program that keeps asking the user to enter a number until they enter 0 1) RECEIVE number FROM KEYBOARD 2) WHILE number = 0 3) RECEIVE number FROM KEYBOARD 4) END WHILE A program that slows speed by 1/10th until speed is no longer more than 5 Draw a flowchart for a program that will ask the user to enter an amount. The program will calculate 10% of that amount. The program keeps asking for the user to enter an amount until they enter 0, when it stops. speed initially 10 acceleration = speed / 10 NOT speed > 5 False True
107
Input Validation Recall that standard algorithms are simple generic algorithms that can be adapted and reused in your program. There is one more standard algorithm you need to know for National 5 – Input validation. Input validation is a standard algorithm that limits what the user can enter as input to a program. If the input is valid, it is accepted and used in program. Invalid input is rejected and the user is prompted to re-enter it until they enter a valid value. You will likely be required to write input validation algorithms in your exam, as well as suggest appropriate values for testing it.
108
Input Validation – Numerical Range
Numerical range input validation limits the numbers that can be entered to a program. One or more comparisons are used to specify which numbers are valid and invalid. This example shows the variable noOfPeople being validated as a non-zero positive number: RECEIVE noOfPeople FROM KEYBOARD WHILE NOT noOfPeople > 0 DO SEND “Number of people must be positive” TO DISPLAY END WHILE Outputs:
109
Numerical range validation usually has both an upper and lower boundary condition. This example shows the user being forced to enter a number between 1 and 10 as part of a guess the number program RECEIVE guess FROM KEYBOARD WHILE NOT (guess ≥ 1 AND guess ≤ 10) DO SEND “You must enter a number between 1 and 10” TO DISPLAY END WHILE Outputs:
110
Input Validation Flow Charts and Structure Diagrams
The same range 1 to 10 program in flow chart and structure diagrams would look like this: Enter guess NOT (guess ≥ 1 AND guess ≤ 10 Enter a guess Repeat while guess not between 1 & 10 False True Display error message Display error message Enter a guess Enter guess
111
Alternative Pseudocodes
RECEIVE guess FROM KEYBOARD WHILE NOT (guess ≥ 1 AND guess ≤ 10) DO SEND error message TO DISPLAY END WHILE WHILE guess < 1 OR guess > 10 DO SEN error message TO DISPLAY REPEAT IF guess < 1 OR guess > 10 THEN END IF UNTIL guess ≥ 1 AND guess ≤ 10 These three examples all function exactly the same! Note the use of inverse conditions. Using NOT is a simple way to invert a condition if you need to.
112
Input Validation - Text
Restricted choice text input validation works by listing all the words that are valid input. If the word entered by the user isn’t on the list, the input is invalid. Remember that comparing strings is case sensitive! This example forces the user to answer a question with either “Yes” or “No”: RECEIVE getDiscount FROM KEYBOARD WHILE NOT (getDiscount = “Yes” OR getDiscount = “No”) SEND “You must enter Yes or No” TO DISPLAY END WHILE Outputs:
113
Testing Input Validation
Input validation should be tested separately from the reliability of the program. You should have a different test table with normal extreme and exceptional data of its own. For numeric range validation: You need one item of normal test data in the middle of each range of acceptable values. You need one item of extreme and one item of exceptional test data for each comparison in the condition. WHILE NOT (guess ≥ 1 AND guess ≤ 10 ) DO 1 x Extreme test data: The number in the comparison, here 1 1 x Exceptional test data: A number outside of the range, below 1 such as -3 1 x Extreme test data: The number in the comparison, here 10 1 x Exceptional test data: A number outside of the range, below 1 such as 12 1 x Normal test data: Any number from middle of range such as 4 or 7
114
WHILE NOT (guess ≥ 1 AND guess ≤ 10 ) DO
Your expected column of the test data should state if the test data will be accepted or rejected by the input validation. Normal and extreme test data should be accepted by input validation, exceptional test data should be rejected. WHILE NOT (guess ≥ 1 AND guess ≤ 10 ) DO For testing restricted choice text input: Test that every entry that should be accepted is. Test one item of text that should be rejected. guess Expected Actual -3 Reject 1 Accept 4 10 12
115
Questions – Input Validation
Answer questions in full sentences! Create sets of test data to fully test the following examples of input validation: An input validation that ensures the user enters a number between 1 & 5 inclusive. An input validation that will only accept the user entering the following football positions – goalkeeper, defender, midfielder and striker. An input validation that ensure the user enters a valid number of marks for a test out of 20.
116
Answer questions in full sentences!
Identify and correct the error in the following program designs Input validation to enter a number between 1 and 10 inclusive N D WHILE Repeat until number > 1 and < 10 Enter a number number < 1 or number > 10 True Display Error message Get number Display error message number ≤ 1 AND number ≥ 10 False Enter number True
117
Answer questions in full sentences!
Write pseudocode for the following input validations: Input validation that will only accept the word “Yes”, “No” and “Maybe”. Input validation that will accept numbers between 5 and 15 inclusive.
118
Predefined Functions A predefined function is a small section of program code that has already been created for you. Predefined functions are useful as they can save you time, and often do things that you would be unable to code yourself. Predefined functions require parameters. This lets you use the same predefined function is several ways. For example, the predefined function to generate random numbers can make numbers from different ranges depending on the parameters you give it. Using the parameters 1 and 10 means our random number will be either 1, 2, 3, 4, 5, 6, 7, 8, 9 or 10
119
Useful Predefined Functions
Random(): Random is a predefined function that generates random numbers within a certain range. Integer() Integer is a function that casts data into the integer data type. Strings and floating point data can be turned into and stored as integers. There are also predefined function to turn data into strings, floating points and booleans. The int() function rounds floating point values down.
120
Round() The round function rounds a floating point value off to a given number of decimal places. It rounds values in the same way used in maths, but can behave oddly because of how floating point values are stored. Length() The length function tells you how many characters are in a string There are many other different predefined functions in addition to these four!
121
Questions – Predefined Functions
Answer questions in full sentences! What is a predefined functions and why are they useful? Explain what is meant by a parameter. List and describe four predefined functions and what they down. Write down the value in the variable speed after each section of pseudocode: SET distance to 5 SET time TO 3 SET speed TO integer(distance/time) SET message TO “Hi There!” SET speed TO length(message)
122
Errors and bugs During the implementation stage of creating software, it is common for the programmers to make mistakes and errors known as bugs. You are required to be able to identify such bugs where they occur, the nature of the error and correct it. Bugs can be identified by testing. Software must be tested in order to find and correct as many bugs as possible before release.
123
Syntax Errors A syntax error is when the programmer has made an error in their use of the programming language. Syntax errors happen when the computer cannot understand what a line of code means. Programs will not compile or run at all if they include a syntax error. This makes it easy to know if your program has a syntax error, though it can still be difficult to find and fix. Most programming environments will highlight where they have encountered the error. This might not be where you have to fix a mistake though.
124
Typical causes of syntax errors include:
Spelling errors – programming keywords and variable names misspelt. Missing symbols – “, &, : or other symbols have been missed out, meaning the computer can’t understand what the program says. Closure error – blocks of code haven’t been closed off properly with brackets or end statements where appropriate. The missing : from the for line will cause a syntax error. Many compilers will highlight the next line as being the source of the error though!
125
Execution Errors Execution Errors are bugs that will not be highlighted when the program is compiled, but will cause the program to crash whilst running. Some execution errors only happen when using specific sets of input data, which can make them very hard to track down. Most programming environments will report at which line an execution error occurred.
126
Typical causes of execution errors include:
Spelling and naming errors – trying to access a variable or object using the wrong name may cause the program to crash. Calculation errors – trying to perform calculations that are impossible such as dividing by 0 will cause the program to crash. The misspelt variable poeple above is assigned the value 0 instead of what the user entered. This will cause a divide by 0 error which will crash the program.
127
Logic Error Logic errors cause a program to process information incorrectly and give the wrong answer. Logic errors do not cause a program to crash or fail to run. Logic errors can only be spotted by testing, and may only occur with specific inputs. This makes them very hard to detect and fix. Logic errors are usually caused by bad design and lack of knowledge This logic error is caused by the programmer not understanding operator precedence.
128
Questions – Errors Answer questions in full sentences!
Describe in detail the three types of errors in a program. In each of the following sections of pseudocode, identify the line at which the error occurs. Write down a corrected version of the line: A Program to calculate the area of a rectangle: 1) RECEIVE length FROM KEYBOARD 2) RECEIVE width FROM KEYBOARD 3) SET area to length * length 4) SEND area TO DISPLAY
129
A program that shares a prize fund between a number of people:
1) RECEIVE prizeFund FROM KEYBOARD 2) RECEIVE numberOfWinners FROM KEYBOARD 3) SET share TO prizeFund / numberWinners 4) SEND “Each winner gets”, share TO DISPLAY A program that checks if someone is 17 or more years old, and is allowed to learn to drive a car: 1) RECEIVE age FROM KEYBOARD 2) IF age < 17 THEN 3) SEND “Can learn to drive” TO DISPLAY 4) ELSE 5) SEND “Can not learn to drive yet” TO DISPLAY 6) END IF
130
Test Tables In the testing stage, software is checked to make sure that it works correctly. In order to test software, the testers must create test data sets and compare the expected results with the actual results the program gives. A test table is used is used to record each set of test data and the results. If the expected and actual results match, you can say your program works correctly. If the results don’t match, there is a bug to fix somewhere!
131
Example test table for a program calculating the perimeter of a rectangle:
Length Width Expected Perimeter Actual Perimeter 20cm 10cm 60cm 5cm 7cm 24cm 13cm 8cm 42cm Calculate the expected results before you run the program. You must select test data sets. Each set should be a list of values for all the inputs of the program. When you run the program, fill in this column with the results the program gives when you type in the inputs in each row.
132
Normal, Extreme & Exceptional Test Data
Test data can be categorised as either normal, extreme or exceptional. At National 5 level, you must select test data so it covers all of these types where appropriate. Normal Test Data: Normal test data includes all the values that the program should accept. Normal test data should be processed correctly and produce the predicted results.
133
Extreme Test Data: Extreme test data is the largest and smallest values that the program should still accept. It should produce the expected results after being processed. In addition, if a program makes a decision using an IF statement, there will be an additional item of extreme data – the value used in the IF. IF age >=17 The value 17 is an item of extreme test data. You should also test two items of normal test data – one above 17 and one below it.
134
Exceptional Test Data: Exceptional test data is outside the range of acceptable values for your program. Exceptional test data should be rejected by the program and the user prompted to re-enter. You should include one item of exceptional test data for each range of unacceptable values. For example, if your program only accepts numbers between 1 and 10, you need two items of exceptional test data – one below 1, and one above 10.
135
Documentation – Code Readability
At National 5 level, you are expected to make code readable. If program code is readable, another programmer can look at it and easily understand what it does. There are a number of steps you can take to make program code readable: Internal Commentary: Comments are lines of a program that are ignored by the computer. Adding comments that explain what each section of the program does makes it more readable.
136
Meaningful Identifiers: Pick variable names and other identifiers that make it clear what the variable is used to store. For example circleArea makes it clear what variable store, a does not. Indentation: Indentation is when white space is placed at the start of a line of code to make it clear that it is inside another block of code. The contents of loops and if statements should be indented. White Space: The addition of empty lines between blocks of code breaks up the program and makes it easier to see which part of the program does what.
137
Questions – Testing & Documentation
Answer questions in full sentences! Describe the three types of test data? Describe four ways in which code can be made more readable. A program takes in a test mark between 0 and 20. The input is validated. Copy the following test table and fill in the test mark and expected result columns with whether or not the data should be accepted. Type of data Test mark Expected result Actual result Exceptional Extreme Normal
138
Copy and complete the inputs and expected columns of the test table.
A program calculates the average temperature in three rooms. It displays the average and a message if the heating should be on or off. The heating should be on if the temperature is less than 17oC. Copy and complete the inputs and expected columns of the test table. Type of data Room 1 temp Room 2 temp Room 3 temp Expected average Expected on/off message Actual average Actual on/off message Normal Extreme
139
Evaluation In the evaluation stage, the software is judged in terms of how good it is. At National 5 level, there are four considerations you should use to judge if a program is good: Fit for purpose – does it solve the problem set out at the start of the development process. Efficient use of coding constructs – does it complete it’s task in the minimum number of lines of code? Robustness – can the software handle errors without crashing? Readability – is the program code easy to read, using meaningful variable and subprogram names, and internal commentary? You have already learned how to ensure how some of these criteria are met earlier: Testing shows fitness for purpose. Robustness can be ensured by using input validation. Readability is covered by including appropriate documentation.
140
Efficiency – Repetition
Efficient code makes use of conditional and fixed loops to repeat lines of code: Initialise total to 0 Initialise total score to 0 Enter score Initialise times to 1 These lines are repeated multiple times. This is inefficient. Add score to total True Enter score i = 6 Add score to total False Enter next score Enter score Add score to total Add next score to the total score Enter score Add score to total Add 1 to times Enter score Merge the repeated lines inside a loop to make it more efficient. Add score to total
141
Efficiency – Use of Arrays
Efficient code makes use of arrays to store a list of similar variables: RECEIVE num1 FROM KEYBOARD RECEIVE num2 FROM KEYBOARD RECEIVE num3 FROM KEYBOARD RECEIVE num4 FROM KEYBOARD RECEIVE num5 FROM KEYBOARD SET total TO num1 + num2 + num3 + num4 + num5 SET average TO total / 5 SEND average TO DISPLAY FOR i FROM 1 TO 5 DO RECEIVE num[i] FROM KEYBOARD SET total TO total + num[i] END FOR SET average TO total / 5 SEND average TO DISPLAY Use an array instead. You can then use a fixed loop and the loop control variable to remove the repetition. This program uses five different variables, which is inefficient as it leads to repetition.
142
Efficiency – Complex Conditions
Efficient code uses complex conditions instead of multiple simple conditions RECEIVE mark FROM KEYBOARD IF mark < 70 THEN IF mark ≥ 60 THEN SET grade TO “B” END IF SEND grade TO DISPLAY RECEIVE mark FROM KEYBOARD IF mark ≥ 60 AND mark < 70 THEN SET grade TO “B” END IF SEND grade TO DISPLAY By using a complex condition instead of two simple ones, the number of lines of code in the program is reduced
143
Efficiency – Nesting IF Statements
Efficient code uses ELSE IF or nested IF statements: What Grade? mark ≥ 70 mark ≥ 60 & < 70 mark ≥ 50 & < 50 mark < 50 True True True True grade = “A” grade = “Fail” grade = “B” grade = “C” This design always makes 4 comparisons, regardless of the value in mark. What Grade? Place the other conditions inside each other, as they should not be evaluated if the previous condition is true. The design now makes only 1 to 3 comparisons. mark ≥ 70 False True mark ≥ 60 & < 70 False grade = “A” True mark ≥ 50 & < 60 grade = “B” True False grade = “C” grade = “Fail”
144
Questions – Evaluation & Efficiency
Answer questions in full sentences! Describe in detail the four criteria used to evaluate programs. Rewrite each of the following program designs to make them more efficient. . 1) RECEIVE name_1 FROM KEYBOARD 2) RECEIVE name_2 FROM KEYBOARD 3) RECEIVE name_3 FROM KEYBOARD 4) SET total TO length(name_1) 5) SET total TO total + length(name_2) 6) SET total TO total + length(name_3) 7) SEND total TO DISPLAY
145
. Running Total Input result result > 20 True False result < 10
Print “Merit” False result ≤ 20 and ≥ 10 Print “Fail” True False Print “Acceptable” Running Total Repeat 10 times Initialise total score to 0 Repeat 10 times Display total Enter a new score and store it in an array Add score at loop index in array to total
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.