Programming Constructs Notes Software Design & Development: Computational Constructs, Data Types & Structures, Algorithm Specification
Contents Subprograms Questions Questions Standard Algorithms Questions Questions Complex Data Types Questions Questions File Handling Questions Questions
Subprogram A subprogram is a block of code in a program that is semi independent from the rest of the program. Subprograms are used in computing because they make a program more readable and modular. Subprograms can be reused by calling them multiple times in a program – they can even be imported into other programs as a part of a library. This is especially important for large programs, where work is split amongst several programmers. A programmer can be tasked to write a subprogram given its header. The header of a subprogram is enough for other programmers to call that subprogram in the code that they are writing. This way they programmers can work independently.
Parameters The parameters of a subprogram are variables that are passed to that subprogram from the part of the program that calls it. By passing different variables to a subprogram as its parameters, the same subprogram can give different results. This allows the same code to be reused multiple times. A subprogram can only use the values that are passed to it, along with any other local variables it creates itself. It cannot access variables created elsewhere in the program
Call by Reference & Call by Value In programming, the parameters passed into a subprogram use one of two differing methods: call by reference and call by value. Different programming languages use different methods - in some cases they use both! With call by value, a copy of the values stored in the variables is passed into the subprogram. If any changes are made to those values inside the program, the changes are not made to the original variables used in the subprogram call. Variables in Python are passed using call by value With call by reference, the memory location of the parameter is passed to the sub program. This means that any changes made to the value stored in the variable will persist outside of the subprogram.
Local & Global Variables All variable have a scope. The scope of a variable is where within the program that the variable can be seen and used Global variables can be accessed throughout the entire program Using global variables is considered to be bad practice. It ties the programmers to working with specific variables and reduces the reusability of subprograms Local variables can only be accessed in the block of code they were created in Once the program exits the scope of a local variable, the value stored inside it is lost
Functions A function is a type of subprogram that returns a value Because they return a value, you can use a function call as part of a variable assignment, including in a calculation. For example: SET area TO getWidth() * getHeight() Functions need to be defined in order to be used. As well as the body of code used in the function, the function header must include it’s name, any parameters (including their type) and a return type. A function must include a statement to return a value to the part of the program that called it. FUNCTION getArea (float length, float width) RETURNS float …function code goes in here… RETURN area END FUNCTION Some programming languages do not require functions to be defined in such detail though
Procedures A procedure is a type of subprogram that completes a given task. Unlike functions, procedures do not return a value Therefore, procedure calls are only made independent statements. They can’t be made as part of an assignment. For example: displayArea(area) As well as the body of code used in the procedure, the procedure header must include it’s name and any parameters (including their type). For example: PROCEDURE displayGrades (str[] names, str[] grades) … procedure code goes in here END PROCEDURE Some programming languages do not require functions to be defined in such detail though. Some programming languages do not make a distinction between functions and procedures. The parameters in the header are known as the formal parameters The parameters in the call are known as the actual parameters
Questions – Subprograms Answer questions in full sentences! 1. List two advantages of using subprograms 2. What is meant by the term parameter? 3. Explain the difference between call by reference parameter passing and call by value parameter passing 4. Explain the difference between a function and a procedure 5. What is meant by the scope of a variable 6. Explain the difference between local and global variables 7. Using pseudocode, write a function that returns the circumference of a circle, given its radius
Standard Algorithms Standard algorithms are simple, generic case, algorithms that can easily be adapted and incorporated into a program to solve a simple task You are required to know a number of standard algorithms at Higher level: Input validation Linear search Finding maximums / minimums Counting occurrences You are already familiar with input validation from N5
Input validation Input validation is a standard algorithm that can be used to limit user input. If the user enters an unacceptable input, they are prompted to retry until the input is valid Input validation is important as it can be used to keep programs robust and reliable. Input that can potentially cause a runtime error can be rejected by input validation, as can inputs that would result in nonsensical answers The standard algorithm for input validation is:
Linear Search Linear search is a standard algorithm that identifies if a given value is present in an array or list of values Linear search is only one form of search algorithm. It is relatively inefficient compared to other searches, but does not need the values to be sorted into order Linear searches can be programmed to return a boolean noting if the searched for value is present, or an index or indices where the value is present. The boolean version is:
Finding Max / Min Finding maximum and finding minimum are two very simple standard algorithms that can be used to discover the highest and lowest value in an array respectively Find max / min can be programmed to return either the highest / lowest value, or the index / indices which they are found at. This latter case is useful when using two linked arrays, or two dimensional arrays, as you can use that index to identify other values. For example, finding the highest score, then using the index to find the name of the person who scored it
Here is the simple, finding value, version of finding maximum: Here is the simple, finding value, version of finding minimum:
Counting Occurrences Counting occurrences is a standard algorithm that works out how many of the values in an array or list of values meet a given condition The condition can be something as simple as equalling a particular value, but they can also be complicated conditions made up of many parts The algorithm for counting occurrences is:
You can potentially count many different occurrences at the by including multiple if statements. An example would be exam passes and exam grades: Checking the number of passes would only require a single condition and variable: 1) IF value[i] >= 50 THEN 2) SET passes TO passes + 1 3) END IF Checking the number of different grades would require multiple conditions and variables: 1) IF value[i] >= 70 THEN 2) SET A grades TO A grades + 1 3) END IF 4) IF value[i] >= 60 AND value[i] < 70 THEN 5) SET B grades TO B grades + 1 6) END IF …
Questions – Standard Algorithms Adapt the standard algorithms to write algorithms to solve each of the following problems: 1. The input variable percent must be between 0 and The input variable answer must be either yes, no or maybe 3. Find if any of a list of ten heights is greater than 2 metres 4. Check if the input variable my name is present in an array of 10 names 5. Find the most expensive house in a list of 5 house prices 6. Find the lowest scoring test mark from a class of 30 pupils 7. Find out how many positive numbers are in an array of one hundred values 8. Count the number of As, Bs and C grades in a class of twenty pupils
Complex Data Types - Strings Recall that the string data type stores a series of letters, symbols and numeric characters Strings can be considered to be an array of characters. This opens the possibility of addressing individual characters within the string, and even groups of characters within the string – substrings At Higher level you will be required to manipulate strings including: Splitting strings into substrings and individual characters Concatenating substrings to make new strings Manipulating the individual characters within strings – sort of…
Substrings Individual characters and sections of strings can be accessed. Consider this pseudocode: SET message TO “Hello World!” Then the following pseudocode display lines could be used to output part of that “Hello World!” string literal: SEND message[0] TO DISPLAY – prints the letter “H” SEND message[0:5] TO DISPLAY – prints the word “Hello” Similarly substrings can be concatenated and assigned to other variables: SET letters TO message[0] & message[6] – letters will store “HW”
String Operations Recall that pre-defined functions are already created functions that you can use in your program without having to code yourself There are a number of pre defined functions that can be used to manipulate strings. In Python: len() – returns the length of a string .lower() – returns a lowercase version of the string .strip(char) – removes the specified character from the start and end of the string .split(char) – splits a string into multiple strings using the specified character as a separator .partition(char) – splits a string in two at the first instance of the specified separator character
Manipulating Individual Characters Recall that individual characters are represented in binary using ASCII and Unicode An individual character can therefore also be considered as or converted into a numeric value. This numeric value can be used in the same way as other numeric values Simple arithmetic operations such as + and - can be used to change the value. Comparison operators such as can be used to determine characters position relative to each other in lexicographical order
Records A record is a complex data type that includes multiple named and typed variables. A record can be defined thus: RECORD Person IS {STRING name, INT age} This defines the record of the type Person to contain two variables, a string called name and an integer called age Records are similar to classes in object orientated languages
Assigning Records Records can be assigned to wholly: SET pupil TO Person {“Alice”, 16 } Which creates a new record of the type Person to store Alice’s details Records can be assigned and accessed in part as well: SET pupil.name TO “Carol” Would change the value store in the name variable of the pupil record to be Carol
Questions – Complex Data types Answer questions in full sentences! 1. What is a substring? 2. What is meant by the term concatenating? 3. Explain how the individual characters in a string can have arithmetic and comparison operations carried out upon them 4. List three string operations and describe what they do. Explain why each one might be useful in a program 5. Explain why in some programming languages manipulating strings might be computationally inefficient
6. Explain what is meant by a record 7. Define a record to store the following information a house – its number, street and postcode 8. Create a record of type house called home, filling it with appropriate information
File Handling Previously, all input has come from the KEYBOARD and all output has gone to the DISPLAY Files are an alternate source of input and output for a computer program. A file can contain data which can read into the program. Alternately, a file can have data written to it after the data has been processed by the program. You are required to make use of files for input and output in Higher Computing Science
Reading From Files Before a file can be read from, it must first be opened. In pseudocode: OPEN “myfile.txt” In pseudocode, a file being read from can be treated the same as keyboard input: RECEIVE data FROM “myfile.txt” Most programming languages will read in data on a line by line basis, or as one very long string potentially including carriage return characters. You will typically require to use string operations to break the data into meaningful values for your program. Once finished you should close the file. In pseudocode: CLOSE “myfile.txt”
Writing to files Writing to files is handled similarly. The file must be opened before use and closed when finished with. Alternately a new file can be created instead when writing: CREATE “newfile.txt” Output to a file is the same as output to the screen in pseudocode: SEND “Hello there!” TO “newfile.txt” In practice, different programming languages behave differently when it comes to either writing over existing file contents or appending to previous file contents
Questions – File handling Answer questions in full sentences! 1. What must be done before you can start reading from or writing to a file? 2. What should be done once you are finished reading from or writing to a file? 3. Explain why creating a file can only be used with writing, not reading? 4. Using pseudocode, write a short program which asks the user their name, address and phone number. The program will output this information to a filename of the user’s choice.