Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming Paradigms

Similar presentations


Presentation on theme: "Programming Paradigms"— Presentation transcript:

1 Programming Paradigms
Computing languages So many languages created for different reasons. Fortran – Mathematical applications Cobol – Business Applications Pascal – Training Languages Programming Paradigm This is a fundamental style, or methodology of computer programming. There are several programming paradigms. Imperative (procedural) Functional Logic Event-driven Object-orientated

2 Programming Paradigms
Imperative Programming Programs that are written using sequences of instructions that are executed by the processor in the order the programmer designed. Low level – Machine code, Assembler, fortran, cobol. High level – Pascal, Delphi, C, C++, C# etc.. Functional programming Programs that define mathematical functions. A solution to a problem consists of a series of function calls. There are no variables or assignment statements, but lists and functions that manipulate lists. Logic Programming A logic program consists of a set of facts and rules. A knowledge base is built up through writing facts and rules about a specific area of expertise. Then an inference engine, a program, with an ability to backtrack will use the knowledge base to answer queries presented in the form of a goal. Using Facts and Rules worksheet and strawberry prolog – look at some logical programming. Strawberry Prolog Questions

3 Programming Paradigms
Event Driven Programming An event is an action or occurrence detected by a program. Instead of all the program instructions being executed in the order the programmer designed, subroutines are executed in response to events. Such as clicking a button or choosing a menu option in a form. VBA is an example of an event driven language. Below is an example of a subroutine. Private sub btnSubmit_Click MsgBox(“Hello World”) End sub A continuous system loop processes messages sent from the application and executes the relevant event-handling code.

4 Programming Paradigms
Object Orientated programming Involves breaking down problems into smaller problems. Reusable code is compiled into classes which each have their on methods and data associated with it. These classes form a new “Data Type”. A instant of this new data type is called an object.

5 Object Oriented Programming
Computing Object Oriented Programming

6 Object Class An object class is the collection of methods (or functions) and properties (attributes) that are available to an instance (object) of that class. Classes are used to represent objects that can reflect the real world. An instance of a class is an Objects

7 Object An object is an instance of a particular class.
Which is the object & which is the object class? Lassie Canine Mr Campion Human My Ford Fiesta Car

8 Creating an Object When you create an Object of a class it is Instantiated. You Instantiate an Object. Car Volkswagon; Here I have instantiated an Object of the class Car

9 Encapsulation A Class defines certain methods or functions that each Object of that type will have. It also defines Properties each Object of that type will have

10 Encapsulation The ability to hide the internal properties methods of an object. The user can only to communicate through the public interface. You decide which methods and properties are accessible.

11 Encapsulation Because an Object’s methods and properties are encapsulated, it allows them to be used in code without the programmer needing to understand HOW that function works. If an object NewsAgent responds to a method takeMoney() why do we need to know how the code works?

12 Creating a Class. public class Time { // private variables
private int Year; private int Month; private int Date; private int Hour; private int Minute; private int Second; //public methods public void DisplayCurrentTime() Console.WriteLine("stub for DisplayCurrentTime"); } Variables and methods in classes have what is called Access Modifiers. By default everything is private in a class but it is worth declaring it as such.

13 Creating an object. class Program { static void Main(string[] args)
Time t = new Time(); t.DisplayCurrentTime(); Console.ReadLine(); } Here we create an instance of class Time by declaring it like any normal data type. By declaring an Object of Class Time we can now use the public variables or methods within that class in our program.

14 Access Modifier Restrictions public No restrictions. Members marked public are visible to any method of any class private The members in class A that are marked private are accessible only to methods of class A protected The members in class A that are marked protected are accessible to methods of Class A and also to methods of classes derived from Class A internal The members in class A that are marked internal are accessible to methods of any class in A’s assembly protected internal The members in class A that are marked protected internal are accessible to methods of class A, to methods of classes derived from class A, and to any class in A’s assembly.

15 Constructors class Program { static void Main(string[] args)
Time t = new Time(); t.DisplayCurrentTime(); Console.ReadLine(); } When we create an object of Time we are calling Time() which is called the constructor. This can be overloaded and if omitted, C# will create a default one for you anyway. This is basically the first function that is called when an object is created. Basically it is initialising your object. You can initialise it with different constructors with different parameters (overloading)

16 The overloaded constructor takes in a datetime variable.
Constructors //public methods public void DisplayCurrentTime() { Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Date, Month, Year, Hour, Minute, Second); } //default constructor public Time() //do nothing //overloaded constructor public Time(DateTime dt) Year = dt.Year; Month = dt.Month; Date = dt.Day; Hour = dt.Hour; Minute = dt.Minute; Second = dt.Second; We have changed our Display method and now added two constructors. The default one does not actually need to be created but is put here for future amendments. The overloaded constructor takes in a datetime variable.

17 Constructors class Program { static void Main(string[] args)
Time t = new Time(DateTime.Now); t.DisplayCurrentTime(); Console.ReadLine(); } The creation of an object of Time has now been changed to call the overloaded constructor.

18 Using “this” in classes
//Using this pointer public void SomeMethod(int Hour) { this.Hour = Hour; } The “this” pointer can be used in the methods of the class to refer to that classes methods and and variables. This helps to avoid ambiguity as shown in the example.

19 “Main” is called without having to create an object of “Program”
Static methods in classes class Program { static void Main(string[] args) Time t = new Time(DateTime.Now); t.DisplayCurrentTime(); Console.ReadLine(); } Static methods are methods that can be invoked without having to create an object of the class. The example here is “Main” “Main” is called without having to create an object of “Program” In order to call non-static methods from classes – you need to create an object first.

20 Static constructor in classes
//static variables private static string Name; //static constructor static Time() { Name = "Time"; } //public methods public void DisplayCurrentTime() Console.WriteLine("Name: {0}", Name); Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Date, Month, Year, Hour, Minute, Second); A static constructor is called regardless of any object being invoked – so essentially it is called automatically. You can only use static member variables in static functions.

21 An example of using static methods
public class Cat { private static int instances = 0; public Cat() instances++; } public static void HowManyCats() Console.WriteLine("{0} cats adopted", instances); Here we have a silly example of using static methods in a class. This class has a static method to count how many instances of Cat we have using the static variable instances.

22 An example of using static methods
class Program { static void Main(string[] args) Cat.HowManyCats(); Cat Frisky = new Cat(); Cat Whiskers = new Cat(); Console.ReadLine(); } In the main program we can see that we can access the method without creating an object. The variable is persisted through all creations of the object Cat.

23 Destructors in classes
~Time() { //do work here } A destructor is a method that is automatically called when your object goes out of scope – or you use the delete () method on an object. It is used to clean up any issues – such as closing files or deallocating memory if required.

24 Passing by reference to class methods
public void GetTime(ref int h,ref int m,ref int s) { h = this.Hour; m = this.Minute; s = this.Second; } static void Main(string[] args) Time T = new Time(DateTime.Now); T.DisplayCurrentTime(); int thehour = 0; int theminute = 0; int thesecond = 0; T.GetTime(ref thehour, ref theminute, ref thesecond); Console.WriteLine("Current time: {0}:{1}:{2}", thehour, theminute, thesecond); Console.ReadLine(); You can pass by reference to class methods as well if you want to return more than one of their private variables as access functions can only return one value. In class Time

25 Overloading methods and functions
//overloaded constructor public Time(DateTime dt) { Year = dt.Year; Month = dt.Month; Date = dt.Day; Hour = dt.Hour; Minute = dt.Minute; Second = dt.Second; } public Time(int y,int d,int m, int h, int min,int s ) this.Year = y; this.Month = m; this.Date = d; this.Hour = h; this.Minute = min; this.Second = s; As mentioned before – functions and methods can be overloaded. C# will know which one you are calling based on the parameters applied to it when called.

26 Overloading methods and functions
static void Main(string[] args) { Time t1 = new Time(DateTime.Now); t1.DisplayCurrentTime(); Time t2 = new Time(2005, 11, 18, 11, 03, 20); t2.DisplayCurrentTime(); Console.ReadLine(); } Note the creation of two Time objects invokes two different constructors.

27 Overloading methods and functions
//A property of Time public bool IsSummerTime { get return IsSummerTime; } set IsSummerTime = value; In C# you can create properties in classes that allow you to bypass the usual access methods. There are two defined functions – get and set which work automatically depending on how the property is accessed. See next slide.

28 You can add access modifiers to the functions get and set.
Overloading methods and functions static void Main(string[] args) { Time t1 = new Time(DateTime.Now); t1.DisplayCurrentTime(); t1.IsSummerTime = false; bool summer = t1.IsSummerTime; Console.ReadLine(); } On the line “t1.IsSummerTime = false” the set method is automatically called. On the “bool summer = t1.IsSummerTime;” the get method is automatically called. You can add access modifiers to the functions get and set.

29 Inheritance Vehicle Car Boat
Base Class Vehicle Is a kind of Is a kind of Car Boat What Methods or Properties might a car or boat have extra to those of a generic vehicle?

30 Inheritance Human Man Woman
Base Class Human Is a kind of Is a kind of Man Woman What Methods or Properties might a man or woman have extra to those of a generic Human???

31 Class Hierarchies Classes can be arranged in a Hierarchy, such as:
Vehicle Is a kind of Is a kind of Car Boat Is a kind of Hatchback Estate

32 Class Hierarchies In visual C# you could have a class hierarchical structure like this: Control Button Checkbox RadioButton Command Listbox Etc..

33 The constructor takes in three values to initialise the variables.
Inheritance in C# class Vehicle { protected string Fuel; protected decimal Price; protected int topspeed; public void SetFuel(string f) {Fuel = f;} public string GetFuel() { return Fuel; } public void SetPrice(decimal p) { Price = p; } public decimal GetPrice() { return Price; } public void SetTopSpeed(int t){topspeed = t;} public int GetTopSpeed() { return topspeed; } protected Vehicle() { } protected Vehicle(string f, decimal p, int s) Fuel = f; Price = p; topspeed = s; } protected void ShowDetails() Console.WriteLine("Fuel: {0}", GetFuel()); Console.WriteLine("Price: {0}", GetPrice()); Console.WriteLine("Top Speed: {0}", GetTopSpeed()); Consider the following base class vehicle. It has variables common to all vehicles and has a ShowDetails method that shows only the base class variables. Note that the method and the variables are protected. The constructor takes in three values to initialise the variables.

34 Note the Constructer has the syntax – base(fuel, price, speed)
Inheritance in C# class Car : Vehicle { private string registration; private int seats; public void SetReg(string r) { registration = r; } public string GetReg() { return registration; } public void SetSeats(int s) { seats = s; } public int GetSeats() { return seats; } public Car(string reg,int seats, string fuel, decimal price, int speed) : base(fuel,price,speed) registration = reg; this.seats = seats; } public void ShowDetails() base.ShowDetails(); Console.WriteLine("Registration: {0}", GetReg()); Console.WriteLine("Seats: {0}", GetSeats()); Here we have a class that is derived from vehicle. It has its own specialised variables and ShowDetails Method. Note the Constructer has the syntax – base(fuel, price, speed) After the declaration – this passes the base constructer the variables it needs. Note – in the ShowDetails method – the base class version is called first

35 Inheritance in C# class Program { static void Main(string[] args)
Car c1 = new Car("AB38FG", 5, "Petrol", 5000M, 130); c1.ShowDetails(); Console.ReadLine(); } In the main function = a new object of car is called and constructed with all the variables required for both the Car and the Vehicle constructors. The ShowDetails call is the derived class method but as seen it will show the base class variables as well.

36 Polymorphism Two different objects that derive from the same base class e.g. Mammal Is a kind of Is a kind of Human Donkey Both have a method called walk() But they do the exact same thing?

37 Containment Cars contain many components.
Therefore an object of the type car would contain many other objects. E.g. engine.

38 OO Design

39 Advantages of OOP Research has shown that, on average, OOP applications: Are composed of a greater number of reusable modules/objects. Have fewer bugs. Are easier to maintain and enhance.

40 Object Orientated Languages

41 Basic C++ Program #include <iostream> using namespace std;
int main(int argc, char *argv[]) { cout<<"HEY, you, I'm alive! Oh, and Hello World!\n"; cin.get(); }

42 C++ Variables int x; int a, b, c, d; Long a; char letter;
float the_float; Double the_double;

43 C++ Variables #include <iostream> using namespace std;
int main(int argc, char *argv[]) { int thisisanumber; cout<<"Please enter a number: "; cin>> thisisanumber; cin.ignore(); cout<<"You entered: "<< thisisanumber <<"\n"; cin.get(); }

44 C++ If Statements > greater than 5 > 4 is TRUE
< less than 4 < 5 is TRUE >= greater than or equal 4 >= 4 is TRUE <= less than or equal 3 <= 4 is TRUE == equal to 5 == 5 is TRUE != not equal to 5 != 4 is TRUE

45 C++ If Statements if ( TRUE ) Execute the next statement {
Execute all statements inside the braces } // Execute these statements if TRUE else // Execute these statements if FALSE

46 C++ If Statements #include <iostream> using namespace std;
int main(int argc, char *argv[]) // Most important part of the program! { int age; // Need a variable... cout<<"Please input your age: "; // Asks for age cin>> age; // The input is put in age cin.ignore(); // Throw away enter if ( age < 100 ) { // If the age is less than 100 cout<<"You are pretty young!\n"; // Just to show you it works... } else if ( age == 100 ) { // I use else just to show an example cout<<"You are old\n"; // Just to show you it works... else cout<<"You are really old\n"; // Executed if no other statement is cin.get();

47 C++ Loops – FOR LOOP int main(int argc, char *argv[]) {
for ( variable initialization; condition; variable update ) {Code to execute while the condition is true} int main(int argc, char *argv[]) { for ( int x = 0; x < 10; x++ ) cout<< x <<endl; } cin.get();

48 C++ Loops – WHILE LOOP #include <iostream> using namespace std;
while ( condition ) { Code to execute while the condition is true } #include <iostream> using namespace std; int main(int argc, char *argv[]) { int x = 0; // Don't forget to declare variables while ( x < 10 ) cout<< x <<endl; x++; // Update x so the condition can be met eventually } cin.get();

49 C++ Loops – DO-WHILE LOOP
{ } while ( condition ); #include <iostream> using namespace std; int main(int argc, char *argv[]) { int x; x = 0; do // "Hello, world!" is printed at least one time // even though the condition is false cout<<"Hello, world!\n"; } while ( x != 0 ); cin.get(); }

50 C++ Functions return-type function_name ( arg_type arg1, ..., arg_type argN );

51 C++ Functions #include <iostream> using namespace std;
int mult ( int x, int y ); int main(int argc, char *argv[]) { int x; int y; cout<<"Please input two numbers to be multiplied: "; cin>> x >> y; cin.ignore(); cout<<"The product of your two numbers is "<< mult( x, y ) <<"\n"; cin.get(); } int mult ( int x, int y ) return x * y;

52 C++ Switch Statement switch ( value ) { case this:
Code to execute if value == this break; case that: Code to execute if value == that break; ... default: Code to execute if value != this or that }

53 Exercise Create a program that gives you 5 menu options An option to log in – The user enters in a username and a pin number An option to Enter in some more users An option to display these details An option to log out Exit program Using functions, Ifs, switch statements,for loops etc. Create a program that does the above. Option 2,3,and 4 cannot be initiated unless number 1 is successful.

54 Class Declaration #include <iostream> using namespace std;
class Computer // Standard way of defining the class { public: // This means that all of the functions below this(and any variables) // are accessible to the rest of the program. // NOTE: That is a colon, NOT a semicolon... Computer(); // Constructor ~Computer(); // Destructor void setspeed ( int p ); int readspeed(); private: // This means that all the variables under this, until a new type of // restriction is placed, will only be accessible to other functions in the // class. NOTE: That is a colon, NOT a semicolon... int processorspeed; };

55 Class Body Computer::Computer() { //Constructors can accept arguments,
// but this one does not processorspeed = 0; } Computer::~Computer() { //Destructors do not accept arguments void Computer::setspeed ( int p ) { // To define a function outside put the name of the class // after the return type and then two colons, and then the name // of the function. processorspeed = p; int Computer::readspeed() { // The two colons simply tell the compiler that the function is part // of the class return processorspeed;

56 Pointers Pointers are aptly named: they "point" to locations in memory
Why use pointers? Use in functions to point to a large area of data rather than copy the data across Handy with classes and new objects – Polymorphism The pointer declaration looks like this: <variable_type> *<name>; e.g. int *points_to_integer;

57 An example of a pointer #include <iostream> using namespace std;
int main() { int x; // A normal integer int *p; // A pointer to an integer p = &x; // Read it, "assign the address of x to p" cin>> x; // Put a value in x, we could also use *p here cin.ignore(); cout<< *p <<"\n"; // Note the use of the * to get the value cin.get(); }

58 Pointers – new and delete keywords
#include <iostream> #include “Header.h” // Header file with “Computer” Class in using namespace std; int main() { Computer *ptr; // A pointer to a Computer class ptr = new Computer(); // Creating a new Object and pointing // to it ptr->setspeed(10) // Call the setspeed function cout<<“The speed is “<<ptr->readspeed()<<endl; cin.get(); delete ptr; }

59 Building House Office Block Stadium Bus Station Hospital Address Size
Bedrooms Garage Address Size Company Workers Address Size Capacity Team Address Size Buses Times Address Size Beds Wards Staff

60 Building Address Size Bedrooms Garage Address Size Company Workers
Capacity Team Address Size Buses Times Address Size Beds Wards Staff

61 Building Address Size House Office Block Stadium Bus Station Hospital
Bedrooms Garage Company Workers Capacity Team Buses Times Beds Wards Staff

62 Inheritance Base Class Derived Class Derived Class Derived Class

63 Base Class Can access all the variables And functions
Protected Public Private Can access all the variables And functions Does not have access to the Variables and functions. Derived Class

64 So…. Inheritance: A relationship among classes where a sub class shares all the fields and methods of a parent class (base class) Exceptions – C++ Private variables and methods are still private.

65 Syntax for inheritance
class Animal { public: Animal(); ~Animal(); void eat(); void sleep(); void drink(); private: int legs; int arms; int age; }; //The class Animal contains information and functions //related to all animal

66 Syntax for inheritance (cont)
class Cat : public Animal { public: Cat(); ~Cat(); int fur_color; void purr(); void fish(); void markTerritory(); }; //each of the above operations is unique //to your friendly furry friends //(or enemies, as the case may be) }

67 int main(int argc, char *argv[])
{ Cat tibbles; Animal *animal_ptr; animal_ptr = new Cat(); tibbles.markTerritory(); animal_ptr->sleep(); tibbles.sleep(); return EXIT_SUCCESS; }

68 Task Create a user input system that allows someone to enter in details of a vehicle. Use a base class – Vehicle and derived classes for different types of vehicles. Use class objects for the different vehicle that users want to enter in.

69 Polymorphism A derived class can implement inherited methods differently if necessary. When new classes are derived from a base class they may redefine some of the base methods. Polymorphism: The same name is used in the class hierarchy for a method but each class may implement this method differently.

70 Polymorphism #include <iostream.h> class base                          //Base Class { public:   void func()   {     cout<<"In base::func()\n";   } }; class d1:public base             // Derived Class 1 { public:   void func()   {    cout<<"In d1::func()\n";   } };

71 What is the outcome??? Polymorphism (cont..)
class d2:public base     // Derived Class 2 { public:   void func()   {    cout<<"In d2::func()\n";   } }; void main() {  d1 d;  base *b=&d;  b->func();  d2 e;  b=&e;  b->func(); } What is the outcome???

72 Polymorphism However – if we make the base function virtual
virtual void func() {   cout<<"In base::func()\n"; } Virtual implies that it is this function – although delcared in the base class – a different one is called. When a base class function is virtual – the derived class equivalent is called instead. What would be the outcome now?

73 class Class1 : public base
class base void func1(); class base virtual void func1(); class Class1 : public base void func1() Output Output Statement 1 Class1 dv; dv.func1() Statement 2 base *bptr; bptr = &dv; bptr->func1()

74 Polymorphism You can make the base class virtual function a pure virtual function if you don’t want the base class function to do anything. virtual void func1() = 0; This means that all derived classes must declare a function with the same name as the base virtual function. It is a forced polymorphism.

75 Task Add to your vehicle task set last lesson a polymorphic virtual function. It must have the same name in all classes – but have different functionality.

76 Recursion Objective – to learn what recursion is and why it is used by trying to solve some example problems with it. Starter: Pick a number between 5 and 10 Work out the Factorial of that number You have 2 minutes to work it out. TIMER

77 Recursion What is recursion?
This is the ability to call itself. For instance a function calling itself within itself. A very powerful technique for solving certain problems. Iteration is the other method and can be more efficient. Good for problems like factorial, binary searches and sorts. Factorial Example: N! = N * (N-1)! Translates to – the number * the number minus 1 reoccuring. 3! = 3 * 2! = 3 * 2 * 1 = 6

78 Recursion What is recursion? Recursive solutions to problems have a general case and a base case. General case – what the function actually does e.g. N! = N * (N-1)! Base case – What stops the function from recursion into infinity e.g. 1! = 1 Lets look at the algorithm for a recursive solution to Factorial calculations. Function Factorial (n : integer) returns integer If N = 1 then return 1 else return n * Factorial(n-1) end if End function. Write this as a program in C++ and ask the user to enter in a number

79 Recursion What happens when the function is called?
Let us say the user enters in 5 as a number. Lets look at the following trace table. int Factorial(long n) { if (n == 1) return 1; else return n * Factorial(n-1); } Call Number Function Call N Result = Return Value 1 2 3 4 5

80 Task Look at questions 1 & 2 on page 82 in your A2 Text Books. Use the following layout for your trace table; Can anyone spot the bug in one of the questions? How would you change the algorithm to fix it. Call Function N Function called Output

81 Plenary What is the general case of a recursion? What is the base case of a recursion? What is the general case of the recursion in question 1 from your tasks. What is the base case of the recursion in question 1 from your tasks.

82 Recursion The Tower of Hanoi SOURCE WORKSPACE DESTINATION
Transfer N-1 discs form source to workspace Move 1 disc from source to destination Transfer n-1 discs from workspace to destination. Solution

83 Recursion Called with MoveTower(4,a,c,b) And so on......... Call N
Function Called Source Destination Workspace 1 4 MT(3,A,B,C) A C B 2 3 MT(2,A,C,B) MT(1,A,B,C) MD(A,B) 3a MD(A,C) MT(1,B,C,A) 5 MD(B,C)

84 Abstract Data Types. Programming languages distinguish between different data types such as integer, real and string. High level languages also provide the programmer with data structures such as records and arrays Object orientated languages all declaration of classes Abstract Data types are closer to real life structures such as lists, queues, stacks.

85 Abstract Data Types - LISTS.
Lists are a dynamic data structure that can shrink or grow. Operations that can be performed on a list are: Initialise list Insert an element Find an element Delete an element Get length of list Output entire list. An array is a form of a linear list where elements are stored in adjacent locations. How can the above operations be performed on an Array (linear list)

86 Abstract Data Types – LINKED LISTS
Linked list are not linear and elements are stored where ever there is a space and pointers point to the next node in sequence. In a linked list node – you have the data item and a pointer pointing to the next node. There is also a special pointer at the start pointing to the beginning of the list. The last node in the sequence has NULL for its pointer. START Fred Jack Matt

87 Abstract Data Types – LINKED LISTS
Insertion of a node. START Fred Jack Matt Ben Ben Ben

88 Abstract Data Types – LINKED LISTS
Deletion of a node. START Fred Jack Matt

89 Abstract Data Types – LINKED LISTS
Programming linked lists You can create a class that has two variables – Data and Pointer. Then create an array of objects of that class. All you need to do is essentially change the pointer values. Start 1 Index DataFields Pointer Fred 2 Jack 3 Matt 4 5 6 Start 1 Index DataFields Pointer Fred 4 2 Jack 3 Matt Greg 5 6 After adding a new node.

90 Abstract Data Types – LINKED LISTS
Programming linked lists Deleting Jack from the list. How can the redundant node in the array be used? A second list can be produced by linking all the free nodes together Start 1 Index DataFields Pointer Fred 4 2 Jack 3 Matt Greg 5 6

91 Abstract Data Types – LINKED LISTS
Linked Lists in C++ Adapt the program to have 3 options. a) Add to list b) Delete from list c) Display list.

92 Abstract Data Types – LINKED LISTS
Many high level languages have a pointer type as a built in data type. A pointer stores an address to the value of the type of data type it is pointing to. When a pointer variable is declared in a program, the compiler will reserve the space in memory for this pointer No space is reserved for the value or values it can point to. This memory space is instead allocated at run time from a pool of memory locations called the HEAP This is known as dynamic allocation. The type of pointer is determined by the value it is pointing to, e.g. Integer pointer, string pointer etc. When a pointer is required to point to a memory location that has the actual value – a special function is called – “New” (In pascal and C++ though used differently in C++) To deallocated this memory another function is called – Dispose (pascal) or delete (C++) Look at how we now apply that to our linked list program to make it more dynamic.

93 Stacks Abstract Data Types – Stacks and queues
Stacks and queues are also abstract data types. They are also dynamic data structres. Seen as special list that differ in the way items are added and removed taken from them Stacks This is known as a last-in, first out abstract data type. Take the word literally – a stack is like a pile of objects, one stacked on top of another. Operations to be performed on a stack – Push – Item is added on top of the stack Pop – item is removed from the top of the stack.

94 Abstract Data Types – Stacks and queues
Stacks are used to store the return address, parameters and register contents when a procedure or functions completes execution, the return address and other data are retrieved from the stack. Stacks are used for compilers, when translating high-level language expressions in assignment structures LOOK AT STATIC STACKS AND DYNAMIC STACKS IN C++ Linda If you tried to push three More items – you would get A “Stack Overflow” error Bert Cynthia Cedric Stack Pointer Albert

95 Abstract Data Types – Stacks and queues
A queue is a FIFO (first in, first out) abstract data type. 2 Operations may be carried out on a queue: Add a new item to the rear of the queue Remove an item from the front of the queue Some examples of use of queues in computing terms Print jobs waiting to be printed Characters entered at the keyboard and held in a buffer Jobs waiting to be executed under a batch operating system Simulations Process list as part of the FDE cycle.

96 Index Data 1 Fred 2 Jack 3 Matt 4 5 6 FP RP So what happens if someone wants to join the end of the queue? The array is full!! A queue after three people have joined it Index Data 1 2 3 Matt 4 Ben 5 Greg 6 Chris FP RP Three more people have joined the queue and two people have left.

97 Abstract Data Types – Stacks and queues
Shuffle Queue One method is to shuffle everyone forward therefore removing the need for a front Pointer. This does however require a lot of assignments, especially if the queue is long Circular Queue The allows the queue to wrap around to the beginning of the array and to use vacated locations. Index Data 1 Zak 2 Amit 3 4 Ben 5 Greg 6 Chris How do we code both versions? Static and Dynamic. FP RP

98 Graphs Graphs are used to solve certain problems e.g. Find a route from one location to another. The London underground map is an example of a graph with the villages and towns represented as an abstract.

99 Graphs We can break a graph down into its individual elements. Edge
Two vertices are neighbours if they are connected by an edge. The degree of a vertex is its number of neighbours. What degree is A? Edge Vertex

100 Graphs Some real life systems can be or are represented by graphs
Vertices Edges Internet Web Pages Hyperlinks Social networks People, actors Friendships, film casts Circuits Resistors, inductors, capacitors, power supplies, transistors, logic gates Wires Transportation Airports Air routes Chemical Compounds Molecules Chemical bonds.

101 Graphs Kevin Bacon Game.
Pick two random actors and try and try to link them together within 6 vertex’s Add another actor to your graph – try and link him/her to one of your original actors. Use to help you.

102 Graphs Labelled Graph / Weighted Graph
A graph in which the edges are labelled, e.g. Miles on a road map. Towns are represented as an abstraction. The edges are the roads and the labels could be the miles between each town. Directed graph Consider the scenario of a football tournament where each team has to play each other. The Arrows indicated where one team has beaten another.

103 Graphs Data representation of a graph. Adjacency Matrix
A graph can be represented as a matrix. Consider the following undirected graph. 1 2 3 4 5

104 Graphs The previous matrix was considered symmetrical.
Directed graphs may not be as one vertex may have an edge to another but not in reverse as the edges are directed. In a directed graph matrix, only the rows are worked out to make the complete matrix. Consider the round robin football tournament: Team A Team B Team C Team D Team E Team F 1

105 Graphs Adjacency List Adjacency lists specify the vertices that are adjacent to each of vertex of the graph. How do you create the adjacent lists for the following undirected graph and directed graph? Vertex Adjacent Vertices 1 2 3 4 5

106 Graphs Adjacency Matrix and lists for labelled/Weighted graphs 1 2 3 ∞
1 2 3 25 45 25 45 Initial Vertex Terminal Vertexes 1 2,25;3,0 2 3,45 3 Answer Questions on Page 110 A2 Text Book

107 Graphs - Paths A sequence of edges that begins at a vertex of a graph and travels from vertex to vertex along edges of a graph – Consider the paths taken with the Kevin Bacon game and the Explorer and travelling salesman problem. A closed path or circuit is a sequence of edges of the form AB,BC,CF,FG,GC,CH,HA where there are links between each path. A cycle is a closed path in which all the edges are different and all the intermediate vertices are different e.g. AB,BC,CD,DE,EF,FG,GH,HA

108 Graphs - Trees A tree is a type of graph that resembles a tree. It is a connected undirected graph with no cycles. There is just one path between each pair of vertices in a tree.

109 Graphs - Trees A rooted tree is a tree which one vertices has been designated as the root and every edge is directed away form the root.

110 Binary Trees Creating a binary tree
Enter in the following into a binary tree for retrieval alphabetically Goldfinch, Dove, Robin, Chaffinch, Blackbird, Wren, Jay, Sparrow, Partridge Goldfinch Dove Robin Jay Wren Chaffinch Sparrow Blackbird Partridge

111 Binary Trees Three ways of traversing a binary tree 1) Preorder
Goldfinch Dove Robin Jay Wren Chaffinch Left side of Node Sparrow Blackbird Partridge Goldfinch Dove Chaffinch Blackbird Robin Jay Partridge Wren Sparrow

112 Binary Trees Three ways of traversing a binary tree 2) In-Order
Goldfinch Dove Robin Jay Wren Chaffinch Bottom of node Sparrow Blackbird Partridge Blackbird Chaffinch Dove Goldfinch Jay Partridge Robin Sparrow Wren

113 Binary Trees Three ways of traversing a binary tree 3) Post-order
Goldfinch Dove Robin Jay Wren Chaffinch Sparrow Blackbird Partridge Blackbird Chaffinch Dove Partridge Jay Sparrow Wren Robin Goldfinch

114 Binary Trees Algorithm to construct a binary tree
Place first item into root node For subsequent items at root node repeat If new item > this node item Then follow right pointer else follow left pointer until pointer = 0; place item at this node

115 Binary Trees Algorithm to search a binary tree Start at the root node
repeat If wanted item is this item then found := true else if wanted item > this item then follow right pointer else follow left pointer until found or null pointer encountered

116 Binary Trees A recursive algorithm for an Preorder tree traversal
Visit the root node Traverse the left subtree Traverse the right subtree

117 Binary Trees A recursive algorithm for an inorder tree traversal
Traverse the left subtree Visit the root node Traverse the right subtree void Tree::InOrder(Node *thisnode) { if (thisnode->pleft != NULL) InOrder(thisnode->pleft); } cout<<thisnode->data<<endl; if (thisnode->pright != NULL) InOrder(thisnode->pright); Goldfinch Dove Sparrow Chaffinch Wren Robin Jay Partridge Blackbird

118 Binary Trees A recursive algorithm for an Postorder tree traversal
Traverse the left subtree Traverse the right subtree Visit the root node

119 Searches and Sorts Linear Search Algorithm for a linear search
While not at end of records if current record = search record – return true Else next record. Efficiency determined by record structure.

120 Searches and Sorts Binary Search Algorithm for a binary search
(findme = record we are searching for) Lowptr = 1 Highptr = no of records Do midptr = (lowptr + highptr) / 2 if record at midptr < findme then lowptr = midptr Endif if recore at midptr > findme then highptr = midptr Until record at midptr = findme Look at the interative version in C++. Can you create the recursive version by using the algorithm on page 117.

121 Searches and Sorts Binary Search
Efficient search algorithm because it removes half of the records each check. A select search of a million records will take up to a million checks maximum. A binary search of a million records will take up to 20 checks max.

122 Searches and Sorts Bubble Sort Algorithm for bubble sort
While not end of list index = 0 compare list[index] and list[index+1] swap if first one is greater than the second and set changes flag index + 1 End while Repeat while changes = true

123 Searches and Sorts - Bubble
Key 6 2 1 3 4 Sorted list 2 6 1 3 4 2 1 6 3 4 Items being swapped 2 1 3 6 4 2 1 3 6 4 2 1 3 6 4 2 1 3 4 6 2 1 3 4 6 2 1 3 4 6 2 1 3 4 6

124 Searches and Sorts - Bubble
Key 1 2 3 4 6 Sorted list 1 2 3 4 6 1 2 3 4 6 Items being swapped 1 2 3 4 6 1 2 3 4 6 1 2 3 4 6 1 2 3 4 6 Etc

125 Searches and Sorts Selection sort Algorithm for selection sort
Find the minimum in the list Swap it with the first item Find the next minimum in the list Swap it with the second item Continue until you have navigated the entire list.

126 Searches and Sorts - Selection
Key 6 2 1 3 4 Sorted list 2 1 3 4 6 1 2 3 4 6 Items being swapped 1 3 2 4 6 1 2 4 6 3 1 2 4 6 3 1 2 4 6 3 1 2 3 6 4 1 2 3 4 6 1 2 3 4 6

127 Searches and Sorts Insertion Sort Algorithm for insertion sort
For every item in input array Sort into output array by inserting it into correct place, one item at a time.

128 Searches and Sorts Insertion Sort Programming Algorithm
Procedure Sort (list,first,last) for currentpointer = first + 1 to last currentvalue = list[currentpointer] pointer = currentpointer – 1 while list[pointer] > currentvalue AND pointer > 0 list[pointer + 1] = list[pointer] pointer = pointer – 1 endwhile list[pointer+1] = currentvalue endfor endprocedure

129 Searches and Sorts Insertion Sort
Using any program language code the previous algorithm and test run it. Use the above program to help you dry run the sorting of the following list.

130 Searches and Sorts - Insertion
Key 6 2 1 3 4 Sorted list 2 6 1 3 4 1 2 6 3 4 1 2 3 6 4 1 2 3 6 4 1 2 3 6 4 1 2 3 4 6 1 2 3 4 6 1 2 3 4 6 1 2 3 4 6

131 Searches and Sorts Quick Sort Algorithm for insertion sort
function quicksort(array) var list less, equal, greater if length(array) ≤ 1 return array select a pivot value pivot from array for each x in array if x < pivot then append x to less if x = pivot then append x to equal if x > pivot then append x to greater return concatenate(quicksort(less), equal, quicksort(greater)) EXAMPLES -

132 Summary Questions Explain why a linear search for data is inefficient
What condition must be true before a binary chop search can be used? A set of 255 records is to be searched. What do you think the maximum number of looks a program will have to take if the data is to be searched: By a linear search By a binary chop search 4) Investigate for yourselves two other types of searches that we have not already covered.


Download ppt "Programming Paradigms"

Similar presentations


Ads by Google