Section Eleven: Programming techniques Flashcards

1
Q

Chapter 53 – Programming basics
What is an algorithm?

A

A sequence of unambiguous instructions for solving a problem.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Chapter 53 – Programming basics
Pseudocode

A

Pseudocode is a way of expressing an algorithm using syntax that is independent of any particular programming language. The algorithm can then be coded in a suitable programming language

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Chapter 53 – Programming basics
Comments

A

A programmer-readable explanation or annotation in the source code of a computer program. They are added with the purpose of making the source code easier for humans to understand, and are generally ignored by compilers and interpreters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Chapter 53 – Programming basics
Data types

A
  • integer a whole number such as -25, 0, 3, 28679
  • real/float a number with a fractional part such as -13.5, 0.0, 3.142, 100.0001
  • Boolean a Boolean variable can only take the value TRUE or FALSE
  • character a letter or number or special character typically represented in ASCII, such as a, A, %, ? or %. Note that the character “4” is represented differently in the computer from the integer 4 or the real number 4.0
  • string anything enclosed in quote marks is a string, for example “Peter”, “123”, or “This is a string”. Either single or double quotes are acceptable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Chapter 53 – Programming basics
Common arithmetic operations

A

The symbols +, -, * and / are used for the common arithmetic operations of addition, subtraction,
multiplication and division.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Chapter 53 – Programming basics
The Round function

A

You can round this number using a function round.
billBetween3 = round(billBetween3,2) //round to 2 decimal places
This will return the value 6.67.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Chapter 53 – Programming basics
Exponentiation

A

If you want to find, for example 25, 5 is called the exponent and you need to use exponentiation.
You can write this operation in pseudocode as
x = 25
or, using variables,
x = y
n

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Chapter 53 – Programming basics
String-handling functions

A

Programming languages have a number of built-in string-handling methods or functions. Some of the common ones in a typical language are:

  • len(string) Returns the length of a string
  • string.find(str) Determines if str occurs in string. Returns index (the position of the first character in the string) if found, and -1 otherwise. In our pseudocode we will assume that string (1) is the first element of the string, though in Python, for example, the first element is string (0)
  • ord(“a”) returns the integer value of a character (97 in this example)
  • chr(97) returns the character represented by an integer (“a” in this example)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Chapter 53 – Programming basics
Constants and variables

A

A constant is a data item whose value cannot change during the program’s execution. Thus, as its name implies – the value is constant.

A variable is a data item whose value can change during the program’s execution. Thus, as its name implies – the value can vary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Chapter 53 – Programming basics
String conversion operations

A
  • int(“1”) converts the character “1” to the integer 1
  • str(123) converts the integer 123 into a string “123”
  • float(“123.456”) converts the string “123.456” to the real number 123.456
  • str(123.456) converts the real number 123.456 to the string “123.456”
  • date(year,month,day) returns a number that you can calculate with
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Chapter 53 – Programming basics
Standards for variable names

A

Guidelines could include:
- Start all variable names with a lowercase letter

  • Do not use underscores in the middle of variable names
  • Use “camelCaps” to separate parts of a variable name – for example, timeInMinutes, maxTemperature
  • Do not use overly long names but keep them meaningful – maxTemp is better than maximumTemperature if there is not likely to be any confusion over the meaning of max
  • Use all uppercase letters for constants, which are then instantly identifiable
  • When defining a class in object-oriented programming, start with an uppercase letter, with the rest of the class name lowercase

Following guidelines such as these will save a lot of time in looking through a program to see whether you called something best_score, Best_Score, bestScore or some other variation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Chapter 54 – Selection
Selection

A

Selection statements are used to select which statement will be executed next, depending on some condition. Conditions are formulated using relational operators.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Chapter 54 – Selection
Relational operators

A

The following operators may be used in pseudocode for making comparisons:
> greater than
< less than
>= greater than or equal
<= less than or equal
== equal
!= not equal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Chapter 54 – Selection
The switch/case statement

A

Some programming languages support the use of a switch or case statement, an alternative structure to a nested if statement. It is useful when a choice has to be made between several alternatives.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Chapter 54 – Selection
Boolean operators AND, OR, NOT

A

More complex conditions can be formed using the Boolean operators AND and OR.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Chapter 54 – Selection
The NOT operator

A

You can usually avoid the use of the NOT operator, replacing it with an appropriate condition. e.g.
NOT (a = b) is equivalent to a != b
NOT (a < b) is equivalent to a >= b

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Chapter 54 – Selection
The XOR operator

A

XOR stands for exclusive OR, so that a XOR b means “either a or b but not both”.
This can be implemented with a combination of AND, OR and NOT conditions:
(a AND NOT b) OR (NOT a AND b)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Chapter 55 – Iteration
Performing a loop

A

The third basic programming construct is iteration. Iteration means repetition, so iterative statements always involve performing a loop in the program to repeat a number of statements. There are three different types of loop to be
considered, although some programming languages do not implement all three.

17
Q

Chapter 55 – Iteration
The while / endwhile loop

A

A while … endwhile loop has two properties:
- The expression controlling the repetition of the loop must be of type Boolean – that is, one which evaluates to True or False
- This expression is tested at the start of the loop

18
Q

Chapter 55 – Iteration
The repeat until loop

A

This type of loop is very similar to the while … endwhile loop, with the difference that the Boolean expression controlling the loop is written and tested at the end of the loop, rather than at the beginning. This means that the loop is always performed at least once.

19
Q

Chapter 55 – Iteration
The for next loop

A

This type of loop is useful when you know how many iterations need to be performed. For example, suppose you want to display the two times table:
for count = 2 to 12
product = 2 * count
print(“2 x “, count, “ = “, product)
next count
The value of count starts at 2 and is incremented each time round the loop. When it reaches 12, the loop terminates and the next statement is executed.

20
Q

Chapter 56 – Subroutines and recursion
Types of subroutine

A

A subroutine is a named block of code which performs a specific task within a program. Most high-level languages support two types of subroutine, functions and procedures, which are called in a slightly different way. Some languages such as Python have only one type of subroutine,
namely functions. All programming languages have ‘built-in’ functions which you will have already used if you have written any programs. For example, in Python:
myName = input(“What is your name? “)
print(“Hello, “, myName)

21
Q

Chapter 56 – Subroutines and recursion
Passing parameters by value and by reference

A

Frequently, you need to pass values or variables to a subroutine. The exact form of the subroutine interface varies with the programming language, but will be similar to the examples below:

procedure subroutineName(parameter1, parameter 2,…)
function subroutineName(parameter1, parameter 2,…)

In some programming languages, parameters may be passed in different ways. If a parameter is passed by value, its actual value is passed to the subroutine, where it is treated as a local variable. Changing a parameter inside the subroutine will not affect its value outside the subroutine.

All parameters are passed by value in Python.

In Visual Basic or Pascal, parameters may be passed by value but they may also be passed by reference. In this case, the address, and not the value, of the parameter is passed to the subroutine. Therefore, if the value is multiplied by three, for example, its value in the main program will reflect that change since it is referring to the same memory location.

To pass by reference in Pascal, the procedure header will specify that the relevant parameter is a variable.
For example:
procedure abc(x, y : integer; var z : integer;)
Here, x and y are passed by value and z is passed by reference.

22
Q

Chapter 56 – Subroutines and recursion
Local and global variables

A

Variables used in the main program are by default global variables, and these can be used anywhere in the program, including within any subroutines. Within a subroutine, local variables can be used within the subroutine, and these exist only during the execution of the subroutine. They cannot be accessed outside the subroutine and changing them has no effect on any variable outside the subroutine, even if the variable happens to have the same name as the local variable.

In Python, variables used in subroutines are local by default, unless they are declared as global in the calling program.

23
Q

Chapter 56 – Subroutines and recursion
Programming with subroutines

A

Using subroutines in a large program has many advantages:
- A subroutine is small enough to be understandable as a unit of code. It is therefore relatively easy to understand, debug and maintain especially if its purpose is clearly defined and documented
- Subroutines can be tested independently, thereby shortening the time taken to get a large program working
- Once a subroutine has been thoroughly tested, it can be reused with confidence in different programs or parts of the same program
- In a very large project, several programmers may be working on a single program. Using a modular approach, each programmer can be given a specific set of subroutines to work on. This enables the whole program to be finished sooner
- A large project becomes easier to monitor and control

24
Q

Chapter 56 – Subroutines and recursion
Definition of a recursive subroutine

A

A subroutine is recursive if it is defined in terms of itself. The process of executing the subroutine is called recursion. A recursive routine has three essential characteristics:
- A stopping condition or base case must be included which when met means that the routine will not call itself and will start to ‘unwind’
- For input values other than the stopping condition, the routine must call itself
- The stopping condition must be reached after a finite number of calls

Recursion is a useful technique for the programmer when the algorithm itself is essentially recursive.

Some algorithms can be written using either recursion or iteration. Recursive routines are often much shorter, but more difficult to trace through. If a recursive routine is called a very large number of times before the stopping condition is reached, the program may crash with a “Stack overflow” error (see below, “Use of the call stack”). An iterative routine, on the other hand, has no limit to the number of times it may be called.

25
Q

Chapter 57 – Use of an IDE
Facilities of an IDE

A

When you create a program you will be using a software package that helps you write the code more
easily.
This is called an Integrated Development Environment or IDE.
The screenshot below shows the Komodo IDE being used.

26
Q

Chapter 57 – Use of an IDE
Compiling and running your program

A

When you are ready to try out your program, it first has to be translated into machine code. This will be done using a compiler or interpreter.
Double-clicking the option Save and Run in the Toolbox on the right of the window in the Komodo IDE will translate the program and report any syntax errors.

Logic errors are usually much more difficult to find than syntax errors.
The IDE has various tools to help you.
- You can set a breakpoint in the program which will cause the program to stop on that line, so that you can see whether it reaches that line.
- You can set a watch on a variable so that its value is displayed each time it changes
- You can step through a program a line at a time so that you can see what is happening

27
Q

Chapter 57 – Use of an IDE
Test strategies

A

Testing your own software
Devising a test plan
Dry-running a program

28
Q

Chapter 57 – Use of an IDE
Testing your own software

A

You will have implemented several algorithms in your practical sessions. Testing your solutions for correctness can be a complex and time-consuming task, but one that needs to be done thoroughly and systematically.
The purpose of testing is not to show that your program usually works correctly, if the user is careful when entering input data. The purpose of testing is to try and uncover undetected errors.

29
Q

Chapter 57 – Use of an IDE
Devising a test plan

A

Your program should work correctly whatever data is input. If invalid data is entered, the program should detect and report this, and ask the user to enter valid data. Some data may be valid, but may nevertheless cause the program to crash if you have not allowed for particular values.

We need to choose test data that will test the outcome for any user input. To do this, we need to select normal, boundary and erroneous data.
- normal data is data within the range that you would expect, and of the data type (real, integer, string, etc. that you would expect. For example, if you are expecting an input between 0 and 100, you should test 1 and 99
- boundary data is data at the ends of the expected range for example, test 0 and 100 to make sure that these give the expected results if the valid range is between 0 and 100
- erroneous data is data that is either just outside an expected range, e.g. -1, 101 or is of the wrong data type – for example, non-numeric characters when you are expecting a number to be input

For each test, you should specify the purpose of the test, the expected result and the actual result.

30
Q

Chapter 57 – Use of an IDE
Devising a test plan

A

Your program should work correctly whatever data is input. If invalid data is entered, the program should detect and report this, and ask the user to enter valid data. Some data may be valid, but may nevertheless cause the program to crash if you have not allowed for particular values.

We need to choose test data that will test the outcome for any user input. To do this, we need to select normal, boundary and erroneous data.
- normal data is data within the range that you would expect, and of the data type (real, integer, string, etc. that you would expect. For example, if you are expecting an input between 0 and 100, you should test 1 and 99
- boundary data is data at the ends of the expected range for example, test 0 and 100 to make sure that these give the expected results if the valid range is between 0 and 100
- erroneous data is data that is either just outside an expected range, e.g. -1, 101 or is of the wrong data type – for example, non-numeric characters when you are expecting a number to be input

For each test, you should specify the purpose of the test, the expected result and the actual result.

31
Q

Chapter 57 – Use of an IDE
Dry-running a program

A

A useful technique to locate an error in a program is to perform a dry run, with the aid of a trace table.
As you follow through the logic of the program in the same sequence as the computer does, you note down in the trace table when each variable changes and what its value is.

32
Q

Chapter 58 – Use of object-oriented techniques
Procedural programming

A

Programming languages have been evolving ever since the development of assembly languages. High level languages such as Basic and Pascal are known as procedural languages, and a program written in one of these languages is written using a series of step-by-step instructions on how to solve the problem. This is usually broken down into a number of smaller modules, and the program then consists of a series of calls to procedures or functions, each of which may in turn call other procedures or functions.

In this method of programming, the data is held in separate primitive variables such as integer or char, or in data structures such as array, list or string. The data may be accessible by all procedures in the program (global variables) or local to a particular subroutine. Changes made to global data may affect other parts of the program, either intentionally or unintentionally, and may mean other subroutines have to be modified.

33
Q

Chapter 58 – Use of object-oriented techniques
Object-oriented programming

A

In object-oriented programming, the world is viewed as a collection of objects. An object might be a person, animal, place or event, for example. It could be something more abstract like a bank account or a data structure such as a stack or queue that the programmer wishes to implement.

An object-oriented program is composed of a number of interacting objects, each of which is responsible for its own data and the operations on that data. Program code in an object-oriented program creates the objects and allows the objects to communicate with each other by sending messages and receiving answers. All the processing that is carried out in the program is done by objects.

34
Q

Chapter 58 – Use of object-oriented techniques
Object attributes and behaviours

A

Each object will have its own attributes. The attributes of a car might include its make, engine size, colour, etc. The attributes of a person could include first name, last name, date of birth.

35
Q

Chapter 58 – Use of object-oriented techniques
Classes

A

A class is a blueprint or template for an object, and it defines the attributes and behaviours (known as methods) of objects in that class. An attribute is data that is associated with the class, and a method is a functionality of the class – something that it can do, or that can be done with it.

For example, a stock control system might be used by a bookshop for recording the items that it receives into stock from suppliers and sells to customers. The only information that the stock class will hold in this simplified system is the stock ID number, stock category (books, stationery, etc.), description, and quantity in stock.

36
Q

Chapter 58 – Use of object-oriented techniques
Instantiation (creating an object)

A

A constructor is used to create objects in a class. In this pseudocode, a procedure with the name new is a constructor.

Once the class and its constructor have been defined, and each of the methods coded, we can start creating and naming actual objects. The creation of a new object (an instance of a class) is known as instantiation. Multiple instances of a class can be created which each share identical methods and attributes, but the values of those attributes will be unique to each instance.

Suppose we want to create a new stock item called book1. The type of variable to assign to book1 has to be stated. This will be the class name, StockItem. The word new is typically used to instantiate (create) a new object in the class.

37
Q

Chapter 58 – Use of object-oriented techniques
Sending messages

A

Messages can be categorised as either “getter” or “setter” messages. In some languages, “getter” messages are written as functions which return an answer, and “setter” messages as procedures which change the state of an object. This is reflected in the pseudocode used in this book.

The state of an object can be examined or changed by sending it a message, for example to get or increase the quantity in stock. To get the quantity in stock of book1,
for example, you could write:
quantity = book1.GetQtyInStock

To record the sale of three book1 objects, you could write
book1.SellStock(3)

38
Q

Chapter 58 – Use of object-oriented techniques
Encapsulation

A

An object encapsulates both its state (the values of its instance variables) and its behaviours or methods. All the data and methods of each object are wrapped up into a single entity so that the attributes and behaviours of one object cannot affect the way in which another object functions.

Encapsulation is a fundamental principle of object-oriented programming and is very powerful. It means, for example, that in a large project different programmers can work on different classes and not have to worry about how other parts of the system may affect any code they write. They can also use methods from other classes without having to know how they work.

Related to encapsulation is the concept of information hiding, whereby details of an object’s instance variables are hidden so that other objects must use messages to interact with that object’s state. To change the volume of the Roberts radio, for example,
a programmer might write:
robertsRadio.setVolume(5)

39
Q

Chapter 58 – Use of object-oriented techniques
Inheritance

A

Classes can inherit data and behaviour from a parent class in much the same way that children can inherit characteristics from their parents. A “child” class in object-oriented program is referred to as a subclass, and a “parent” class as a superclass.

For example, we could draw an inheritance hierarchy for animals that feature in a computer game. Note that the inheritance relationship in the corresponding inheritance diagram is shown by an unfilled arrow at the “parent” end of the relationship.

40
Q

Chapter 58 – Use of object-oriented techniques
When to use inheritance

A

There is a simple rule to determine whether inheritance is appropriate in a program, called the “is a” rule, which requires an object to have a relationship to another object before it can inherit from the object. This rule asks, in effect, “Is object A an object B”? For example, “Is a Cat an Animal?” “Is a Mouse a Rodent?” Technically, there is nothing to stop you coding a program in which a man inherits the attributes and methods of a mouse, but this is going to cause confusion for users!

41
Q

Chapter 58 – Use of object-oriented techniques
Polymorphism

A

Polymorphism refers to a programming language’s ability to process objects differently depending on their class. For example, all objects in subclasses of Animal can execute the methods moveLeft, moveRight, which will cause the animal to move one space left or right.

We might decide that a cat should move three spaces when a moveLeft or moveRight message is received, and a Rodent should move two spaces. We can define different methods within each of the classes to implement these moves, but keep the same method name for each class.

Defining a method with the same name and formal argument types as a method inherited from a superclass is called overriding. In the example above, the moveLeft method in each of the Cat and Rodent classes overrides the method in the superclass Animal.