Queues Chapter 3. Objectives Introduce the queue abstract data type. – Queue methods – FIFO structures Discuss inheritance in object oriented programming.

Slides:



Advertisements
Similar presentations
COSC 1P03 Data Structures and Abstraction 9.1 The Queue Whenever you are asked if you can do a job, tell 'em, "Certainly, I can!" Then get busy and find.
Advertisements

1 Data Structures CSCI 132, Spring 2014 Lecture 8 Implementing Queues.
LINKED QUEUES P LINKED QUEUE OBJECT Introduction Introduction again, the problem with the previous example of queues is that we are working.
Chapter3 QUEUES.
Queue Overview Queue ADT Basic operations of queue
Data Structures Chapter 3 Queues Andreas Savva. 2 Queues A data structure modeled after a line of people waiting to be served. A data structure modeled.
Data Structures Chapter 4 Linked Stacks and Queues Andreas Savva.
True or false A variable of type char can hold the value 301. ( F )
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
The If/Else Statement, Boolean Flags, and Menus Page 180
Administrative MUST GO TO CORRECT LAB SECTION! Homework due 11:59pm on Tuesday. 25 points off if late (up to 24 hours) Cannot submit after 11:59pm on Wednesday.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Data Structures Chapter 2 Stacks Andreas Savva. 2 Stacks A stack is a data structure in which all insertions and deletions of entries are made at one.
Object Oriented Data Structures
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
Pointers OVERVIEW.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Introduction to Stacks Chapter 2. Objectives Introduce abstract data types. Discuss implementation types. – Static – Dynamic – Contiguous Introduce the.
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. CIS_IS20_CSLO 1. Explain computer programming concepts CSLO1.6. Explain the purpose of general.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Compound Statements If you want to do more than one statement if an if- else case, you can form a block of statements, or compound statement, by enclosing.
Kruse/Ryba ch041 Linked Stacks and Queues Pointers and Linked Structures Linked Stacks Linked Stacks with Safeguards Linked Queues Application: Polynomials.
C++ Programming Lecture 7 Control Structure I (Selection) – Part II The Hashemite University Computer Engineering Department.
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
1 Data Structures CSCI 132, Spring 2014 Lecture 6 Applications using Stacks.
Chapter 3 Working with Batches of Data. Objectives Understand vector class and how it can be used to collect, store and manipulate data. Become familiar.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Kruse/Ryba ch031 Object Oriented Data Structures Queues Implementations of Queues Circular Implementation of Queues.
Kruse/Ryba ch031 Object Oriented Data Structures Queues Implementations of Queues Circular Implementation of Queues.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Variables  A piece of memory set aside to store data  When declared, the memory is given a name  by using the name, we can access the data that sits.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
1 Data Structures CSCI 132, Spring 2016 Notes 6 Applications using Stacks.
Algorithms JPC and JWD © 2002 McGraw-Hill, Inc. 2 Algorithms 2 An Algorithm is a finite set of precise instructions for performing a computation or for.
1 Data Structures CSCI 132, Spring 2016 Notes13 Queues as Linked Lists, Polynomial Arithmetic.
1 Data Structures CSCI 132, Spring 2014 Lecture 7 Queues.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Chapter 1.2 Introduction to C++ Programming
Chapter 3 Selection Statements
Chapter Topics The Basics of a C++ Program Data Types
REPETITION CONTROL STRUCTURE
Chapter 1.2 Introduction to C++ Programming
Basic Elements of C++.
EGR 2261 Unit 4 Control Structures I: Selection
Variables A piece of memory set aside to store data
Linked Stacks and Queues
Basic Elements of C++ Chapter 2.
More Selections BIS1523 – Lecture 9.
تهیه کنندگان مهری بابائی،گیتا جوادی رضا امید ملایری ،ناصر بهمدی
Additional Control Structures
Chapter 7 Additional Control Structures
Chapter 7 Conditional Statements
Control Structures Part 3
C++ Programming Lecture 7 Control Structure I (Selection) – Part II
Presentation transcript:

Queues Chapter 3

Objectives Introduce the queue abstract data type. – Queue methods – FIFO structures Discuss inheritance in object oriented programming. – Extending a class Implement contiguous queues. – Circular arrays Introduce the switch statement.

Homework Overview Written (max 10 points) – 3.1 E1 (a,b,c)(2 pts each) – 3.1 E2 (a,b)(4 pts) Programming (max 22 points) – 3.3 E4(8 pts) – 3.3 P1(10 pts) – 3.4 P1(8 pts) – 12 Days (10 pts) Group Project (12 points) – 3.3 E2 (a,b,c)(12 pts)

Queues Queue – think about people standing in line. We add items at one end (the rear) and remove items at the other (the front). This is a “first-in, first-out” (FIFO) data structure. C++ contains support for a queue container adaptor ( #include ).

Queue Operations A Queue must support the following operations: Create an empty queue. Append – add a new entry at the rear. Serve – remove the entry at the front. Retrieve – get the value of the entry at the front. Empty – determine if the queue is empty.

Queue Class class Queue { public: Queue(); bool empty() const; Error_code serve(); Error_code append(const Queue_entry &item); Error_code retrieve(Queue_entry &item) const; private: … }; We will use the same Error_code enumeration as before.

Extending the Queue Class We may want to add more than the required methods to our abstract data types. For instance we might want to add the following to the queue type. – Full – is the queue full? – Size – How many items are in the queue? – Clear – Empty the queue of all its entries. – Serve-and-retrieve – combine the methods of retrieve and serve.

Extending a Class We may want to add features to a previously defined class. C++ supports this using inheritance. – We define a new class that uses a old one in its definition. class Extended_queue: public Queue{ public: bool full() const; int size() const; void clear(); Error_code serve_and_retrieve(Queue_entry & item); }; An extended queue is a queue, just with new features added.

Homework – Section 3.1 (page 84) Written – E1 (a, b, c) (written on paper) (2 pts each) – E2 (a, b) (written on paper) (4 pts)

Implementing Queues How do we implement a queue? We could use an array were the front is fixed at index 0. Appending an entry is easy. Serving an entry is not.

Implementing Queues Another option would be to allow the front to move in the array. Now serving an entry is easy. The problem is that we just “lost” a slot in the array. – If we do this too many times we will run out of room in the array.

Circular Array To fix this, when we reach the end of the array we can wrap back around to index 0 to append a new item. This will solve the problem but we will need to code this carefully.

Circular Array It can be helpful to think of the array as a circle.

Front and Rear The relationship between front and rear can now be ambiguous. When a queue is full rear = front – 1. When there is one entry rear = front.

Front and Rear When the last item is served, the front moves one space to the right. Now rear = front - 1 again. A full queue and an empty queue look the same! It will be important to have a way to remember if the queue is full or empty.

Queue Math Suppose max is the number of entries in the array. – The array is indexed from 0 to max - 1. We can use modular arithmetic to perform the wrapping. Serve a entry: front = (front + 1) % max; Check to see if the queue is full (or empty): front == (rear + 1) % max;

Queue Math This can also be done using the ternary operator. front = ((front+1) == max) ? 0 : (front +1); It can also be done using an if-else. if((front+1) == max) front = 0; else front = front + 1;

Queue Class class Queue { public: Queue(); // constructor bool empty() const; /* Post: If the Queue is empty, true is returned. Otherwise false is returned. */ Error_code serve(); /* Post: The front of the Queue is removed. If the Queue is empty return an Error_code underflow. */ Error_code append(const Queue_entry &item); /* Post: item is added to the rear of the Queue. If the Queue is full return an Error_code overflow and leave the Queue unchanged. */ Error_code retrieve(Queue_entry &item) const; /* Post: The front fo the Queue retrieved to the output parameter item. If the Queue is empty return an Error_code of underflow. */ protected: int count; int front, rear; Queue_entry entry[maxqueue]; };

Queue Class Notice that the data is protected instead of private. – This will allow us to extend the queue class and have the methods of the new class directly access the data. We will use the count variable to tell if the queue is full or empty.

Queue Code Error_code Queue::append(const Queue_entry &item) /* Post: item is added to the rear of the Queue. If the Queue is full return an Error_code overflow and leave the Queue unchanged. */ { if (count >= maxqueue) return overflow; count++; rear = ((rear + 1) == maxqueue) ? 0: (rear + 1); entry [rear] = item; return success; } Error_code Queue::serve() /* Post: The front of the Queue is removed. If the Queue is empty return an Error_code underflow. */ { if (count <= 0) return underflow; count--; front = ((front + 1) == maxqueue) ? 0: (front + 1); return success; }

Queue Code Error_code Queue::retrieve(Queue_entry &item) const /* Post: The front fo the Queue retrieved to the output parameter item. If the Queue is empty return an Error_code of underflow. */ { if (count <= 0) return underflow; item = entry[front]; return success; } bool Queue::empty() const /* Post: If the Queue is empty, true is returned. Otherwise false is returned. */ { return count == 0; } Queue::Queue() /* Post: The Queue is initialized to be empty.*/ { count = 0; rear = maxqueue - 1; front = 0; }

Extending the Queue Class The methods of the extended queue class will look like the following. int Extended_queue::size() const /* Post: Return the number of entries in the Extended_queue. */ { return count; } Notice that the method can directly access count since it was protected in the original Queue class. This would not work if count were private.

Homework – Section 3.3 (page 91) Written – E4 ( code and be sure to test it) (8 pts) Programming – P1 ( code) (10 pts) Group Project E2 (a, b, c) (test and code) (12 pts)

Queue Testing Code void help() /* Post: A help screen for the program is printed, giving the meaning of each command that the user may enter.*/ { cout << endl << "This program allows the user to enter one command" << endl << "(but only one) on each input line." << endl << "For example, if the command S is entered, then" << endl << "the program will serve the front of the queue." << endl << endl << "The valid commands are:" << endl << "A - Append the next input character to the queue" << endl << "S - Serve the front of the queue" << endl << "R - Retrieve and print the front entry" << endl << "H - This help screen" << endl << "Q - Quit" << endl to continue." << flush; char c; cin.get(c); // flush out an extra newline do { cin.get(c); } while (c != '\n'); }

Queue Testing Code char get_command() /* Post: The user enters a command (A, S, R, H, Q, a, s, r, h, or q). The function returns the command entered. */ { char command; bool waiting = true; cout :"; while (waiting){ cin >> command; command = tolower(command); if (command == 'a' || command == 's' || command == 'r' || command == 'h' || command == 'q') waiting = false; else { cout << "Please enter a valid command:" << endl << "[A]append [S]serve" << endl << "[R]retrieve [H]Help" << endl << "[Q]uit." << endl; } } return command; }

Queue Testing Code bool do_command(char c, Queue &test_queue) /* Pre: c represents a valid command. Post: Performs the given command c on the Queue test_queue. Returns false if c == 'q', otherwise returns true. Uses: The class Queue. */ { bool continue_input = true; Queue_entry x; switch (c) { case 'r': if (test_queue.retrieve(x) == underflow) cout << "Queue is empty." << endl; else cout << endl << "The first entry is: " << x << endl; break; case 'a': cout << "Please enter a character to add to the queue. " << flush; cin >> x; if (test_queue.append(x) == overflow) cout << "Queue is full." << endl; break;

Queue Testing Code case 's': if (test_queue.serve() == underflow) cout << "Queue is empty." << endl; break; case 'h': help(); break; case 'q': cout << "Queue demonstration finished." << endl; continue_input = false; break; } return continue_input; }

Switch Statement Notice the use of the switch statement. – This does the same job as a series of nested if-else statements. The syntax for the switch is switch (expression) { case constant1: group-of-statements-1; break; case constant2: group-of-statements-2; break;... default: default-group-of-statements }

Switch Statement The switch statement works in the following manner: 1.The expression is evaluated. 2.The resulting value is compared to constant1. – If they are equal it executes group-of-statements-1 until it finds the break statement. – When it finds this break statement, the program jumps to the end of the entire switch statement (the closing brace). 3.If expression was not equal to constant1, it is checked against constant2. If it is equal, then it executes group-of-statements-2 until a break is found. 4.This repeats with each value. 5.If the value of expression did not match any of the specified constants, the program executes the statements included after the default label.

Switch Statement One common mistake is to forget the break statements. – The program will continue executing the code for the subsequent cases. – It only stops when it reaches a break. – This is called a “fall-through” structure. – This is a “feature” that can be exploited in some situations. If there is nothing to do in the default case, the default may be omitted. The expression in a switch statement should evaluate to some enumerated type (not float, double, etc.).

Homework – Section 3.4 (page 93) Programming – P1 (Modify the queue testing program to test the Extended_queue class methods.)( code) (8 pts) – Write a program that exploits the fall- through feature of the switch statement to print out the lyrics to the 12 Days of Christmas. Use as few output statements as possible. ( code) (10 pts)