Learning Outcomes
• Describe the fundamental programming concepts of sequence, selection and iteration, including count-controlled and condition-controlled loops.
• describe how algorithms can be represented using flowcharts;
• explain the terms algorithm, syntax, data type and variable;
• explain object-oriented programming terminology: objects, classes, methods and inheritance; and
• evaluate the use of the object-oriented approach.
Normally, the instructions contained in a program or solution are performed in the order in which they are listed. That is in sequence. This is the simplest control structure. The “Hello world” program and other examples seen in Programming Structure 1 are examples of programs implementing sequential control. The sequence of instructions can contain any number of actions and none can be omitted.
The code shown to the left is an example of how sequence might been used within a program to display a list of options in a menu.
In many programs, the sequence of statements to be performed is determined by the input data. Decisions must be made, based on the values of certain variables, as to which sequence of statements is to be performed. Such decisions require the evaluation of a condition. The result of this evaluation determines which statements are to be executed next.
These take the form of if statements within high level programming languages such as Python. In the example below the computer is selecting what to do based on the variable age.
if age>60:
print("OAP TICKET")
elif age>25:
print("ADULT TICKET")
elif age>18:
print ("STUDENT TICKET")
elif age>4:
print("KID TICKET")
else:
print("FREE ENTRY")
What is a condition? A condition normally describes a particular relationship between a pair of variables or a variable and a constant.
The value of a condition is true if the specified relationship holds for the current variable values; otherwise the condition is false. True can be represented by a 1 and false by a 0. Conditions can be combined using the following logical operators:
• AND
• OR
• NOT
A statement or sequence of statements can be executed more than once (or even not at all) through the use of a loop which can be count-controlled or condition-controlled.
Count-controlled loops
The statements within the loop are executed a number of times which is determined by a loop counter. Example Algorithm to calculate and output the average of 10 integers input by the user.
Begin
Set sum to 0
Repeat 10 times
Input number
Add number to sum
End
repeat average = sum / 10
Output average
End
Different programming languages implement count-controlled loops in different ways. Usually, however, a count-controlled loop is implemented using a FOR statement which typically identifies the following:
• The variable which will control the loop.
• The initial value of the variable.
• The final value of the variable.
• The increment or decrement which is applied to the variable each time the loop is executed which usually defaults to 1.
A sample c# FOR Loop which will repeat 10 times.
for (i=0 ; i<=10 ; i++)
{ Console.WriteLine( i*i); }
A sample Python FOR loop which will repeat 10 times.
For counter in range (1, 10):
print counter
Condition-controlled loops
Frequently the number of times the statements in a loop must be executed cannot be controlled by a counter. A condition-controlled loop can be implemented in one of two ways: Until The loop is executed until a condition becomes TRUE with the condition being tested at the end of the loop. While The loop is executed while a condition is TRUE with the condition being tested at the start of the loop Example Algorithm to calculate how many times the integer 1 must be doubled before the result first exceeds one million.
Begin
Set number to 1
Set count to 0
Repeat
number = number * 2
Increment count
Until number > 1000000
Output count
End
Example Algorithm to calculate and output the average of a sequence of positive integers input by the user. The user indicates the end of the sequence by inputting the dummy value -1. It can be assumed the user inputs at least one positive integer.
Begin
Set sum to 0
Set count to 0
Input number
While number <> -1
sum = sum + number
increment count
Input number
End while
average = sum / count
Output
average
End
Different programming languages implement condition-controlled loops in different ways
An algorithm is a set of rules or steps that represent the solution to a problem. The algorithm is used to help design a solution to a given problem and the order of the steps is important.
Algorithms can be represented in two different ways namely flowcharts and pseudocode.
A flowchart is a diagrammatic representation of an algorithm used in the design stage. It represents the flow of control and the actions required. Flowcharts are visual and the use of the different shapes and lines make them relatively simple to follow.
Flowchart Task
1.Create a flow chart which requests the user to enter 8 numbers and works out the average which is output back to the user.
2.Create a flowchart which prints out all even numbers between 1 and 50. It must use a loop.
3.Create a flowchart for an air conditioning unit which will keep the temperature between 18 and 21 degrees by turning on the heater or the fan accordingly.
All languages have rules governing how statements should be structured. These rules are known as the syntax of the language. In a computer programming language, syntax rules specify how commands should be used to create statements. A statement is a single line of code which performs a task or calculation. A number of statements make up the source code.
Statements can contain many aspects of the language such as: keywords, variables and assignment statements The source code is compiled and the statements are checked to ensure that they follow the syntax rules of the language. If the statements do not follow the syntax rules, a list of compile-time errors will be generated, by the compiler. The programmer will have to correct all of the syntax errors before the program can be fully compiled into machine code.
Different programming languages have their own specific syntax. See the examples of For loops.
Java Tutorials: https://www.w3schools.com/java/default.asp
Python Tutorials: https://www.w3schools.com/python/
A variable is a piece of data held by the computer which can change whilst the program is running. Computer programs will contain many variables for many different purposes and so it is essential we use suitable identifiers when creating variables. This will make the program easier for others to understand our code should they need to maintain the system in the future.
name= "Jim"
gender="male"
yearOfBirth=1997
weight(kg)=88.9
member=True
In the above examples the identifier is to the left of the equal sign. The value after the equal sign is what we are assigning to the variable. The equal sign itself is known as the assignment operator in this context. When a variable name has more than one word we should use either camelcasing or underscores so the text is easily understood by humans.
yearOfBirth (This is camelcasing each new word starts with a capital letter)
year_of_birth (We can also use underscores to separate the words)
It does not matter which method we use as long as we apply the method consistently.
We can also use constants within programs to hold pieces of data, the main difference with a constant is that the data cannot be changed whilst the program is running.
A constant is an item of data which cannot be changed whilst the program is running.
pi=3.14
The main data-types we encouter are:
String- This is a collection of characters (letters, numbers or symbols)
Character- This is one single character (letter, number or character)
Integer- This is a whole number
Real/Float- This is a decimal number
Boolean- This has two possible values, True and False.
Array/List- This is used to store multiple items of similar data using one identifier.
Object-oriented programming makes use of objects when designing and building applications. An object is an element of a program that can perform actions and interact with other elements of the program. When designing a program or application objects are considered first. During the design process objects are defined formally. Once all of the objects have been defined, the building of an application can begin. Objects occur in the real world, for example a car could be described as an object. The car would have certain attributes such as colour, registration number, make, model, engine size and so on. In OOP the attributes that describe objects are called attributes/properties. A car can perform actions for example start ignition, accelerate, brake, stop the engine. In OOP these actions are called methods/behaviours. Methods allow the objects to do things and allow the properties of the object to be manipulated. Objects therefore describe real world elements through the use of methods and properties.
A simple example of the class car could be defined as having the data: Registration Number, Make, Model and Year of Manufacture. A method associated with the class could be to calculate the age of the car on 1st January. Note that a class is only a definition of objects of the same kind. It is an abstract design. That becomes real when Objects are constructed or instantiated from that class. An object is a specific instance of a class that contains real values. An example of an object for this class would be: DUI 78900, Ford, Fiesta, 2000. A class is defined by its name, its data members and its member functions (e.g. methods).
A class encapsulates or hides these elements within its structure (encapsulation). The class can be re-used within a number of applications. Access to data is provided through member functions.
As already indicated, a method is a section of code or procedure contained within a class which defines an action that an object of that class can perform. A class can have a number of methods. The methods only have access to data within their own class. A method is always associated with a class. Examine the code on page 4 and identify the methods associated with the classes.
Inheritance is a fundamental feature of OOP. A new class can inherit the attributes and behaviours of an existing class. In this case the new class is known as a derived, child or sub class. The existing class is known as a base, parent or super class. The derived class inherits all the attributes and behaviours of the base class. The benefit of inheritance is that new attributes and behaviours can be defined for the derived class. In addition, the base class can be re-used to define new more specialised classes. Consider the diagram (Fig 1.). This could represent an inheritance hierarchy. The base class is Person. Both Employee and Student are derived from the base class Person. Both will have the attributes and behaviours associated with a Person. Each will have their own specialised behaviours and attributes.
This tutorial will show you how object oriented programming works in the Python programming language.
https://www.tutorialspoint.com/python/python_classes_objects.htm
Evaluating the use of the Object Oriented approach
The Object Oriented approach is an efficient way of developing applications for the following reasons:
• Classes and methods created for one object oriented application can be reused in other programs and applications. In addition objects can be extended to include other behaviours and attributes. Re-use enables faster development and lowers the overall cost.
• Encapsulation means that once an object is created, it can be used without knowledge of how it is implemented or coded. In addition, objects can hide aspects of themselves from programmers which means that certain parts of the code cannot be altered.
• Due to the modular nature of OOP, designers go through an extensive planning phase. This means better designs with fewer flaws and less time spent on program maintenance.
• The OO approach can also improve software quality. Firstly, a class can be tested in isolation, away from the application in which it is intended to be used. Secondly, with the use of inheritance, the testing of a derived class can assume the base class is correct and can focus on the additional attributes and behaviours. Object oriented programming has some drawbacks which include:
• Concepts including inheritance and encapsulation can be difficult to understand in the first instance meaning that there is a steep learning curve. This means that programmers must learn extensive class libraries before even beginning to program simple applications.
• Object oriented programs can incur run time cost due to dynamic dispatching. This is where the process selects which particular version of a method to call (polymorphism)
Possible Exam Questions
1) Explain suing a suitable example the following three programing techniques:
Sequence (4 Marks)
Selection (4 Marks)
Iteration (4 Marks)
2) Describe the benefits of using iteration when programming? ( 4 Marks)
3) Create an example of a count controlled loop (4 Marks)
4) Create an example of a condition controlled loop (4 Marks)
5) Explain the differences between count controlled loops and condition controlled loops (4 Marks)
Keywords