Review: Expressions, Variables, Loops, and more.

Similar documents
09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

CSC 222: Computer Programming II. Spring 2004

The Stack and Queue Types

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1

SimpleCalc. which can be entered into a TI calculator, like the one on the right, like this:

Programming Abstractions

Stacks and their Applications

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

CS2383 Programming Assignment 3

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

do { statements } while (condition);

Stack Applications. Lecture 27 Sections Robb T. Koether. Hampden-Sydney College. Wed, Mar 29, 2017

CS 106B Lecture 5: Stacks and Queues

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them.

Templates and Vectors

March 13/2003 Jayakanth Srinivasan,

Data Structures and Algorithms

Stack and Its Implementation

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

Introduction to Programming EC-105. Lecture 2

Stack Abstract Data Type

Fundamentals of Programming CS-110. Lecture 2

Formal Languages and Automata Theory, SS Project (due Week 14)

CISC-235. At this point we fnally turned our atention to a data structure: the stack

// The next 4 functions return true on success, false on failure

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Stacks. Revised based on textbook author s notes.

Stating the obvious, people and computers do not speak the same language.

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Programming Abstractions

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

CS 206 Introduction to Computer Science II

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming Fundamentals

Programming Abstractions

CS W3134: Data Structures in Java

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Lecture 8: Simple Calculator Application

Lab: Supplying Inputs to Programs

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Problem with Scanning an Infix Expression

Programming, Data Structures and Algorithms Prof. Hema Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

A First Program - Greeting.cpp

1. In C++, reserved words are the same as predefined identifiers. a. True

CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Stacks Fall 2018 Margaret Reid-Miller

CS 211 Programming Practicum Spring 2017

Project 1: Implementation of the Stack ADT and Its Application

Stack Applications. parsing a postfix expression evaluating postfix expressions. converting infix sums from infix to postfix

Lecture Data Structure Stack

Lecture No.04. Data Structures

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

the Stack stack ADT using the STL stack are parentheses balanced? algorithm uses a stack adapting the STL vector class adapting the STL list class

STACKS AND QUEUES. Problem Solving with Computers-II

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Ch 6. Functions. Example: function calls function

Lecture 4 Stack and Queue

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions

Data Structures using OOP C++ Lecture 9

Postfix (and prefix) notation

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Postfix Notation is a notation in which the operator follows its operands in the expression (e.g ).

! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples:

CS Introduction to Data Structures How to Parse Arithmetic Expressions

First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms...

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Stacks, Queues and Hierarchical Collections

CS 211 Programming Practicum Spring 2018

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \

An Introduction to Trees

Chapter Six: Arrays and Vectors

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11.

C++ Arrays and Vectors

Linked List using a Sentinel

Unit 7. 'while' Loops

CS2255 HOMEWORK #1 Fall 2012

Linear Data Structure

Lecture 12 ADTs and Stacks

CS302 Midterm Exam Answers & Grading James S. Plank September 30, 2010

The following expression causes a divide by zero error:

Assignment 5. Introduction

Lecture 12. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1

15. Stacks and Queues

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1

Why Is Repetition Needed?

Chapter 4 Computation

Infix to Postfix Conversion

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

Transcription:

Review: Expressions, Variables, Loops, and more. 1 An Expression Evaluator Example [2] Wk02.1 Slide 1

2 Case Study : Parsing PostFix Expressions What is an expression? A series of symbols that return some value when evaluated Syntax rules determine if an expression is valid or not Operators act on expressions to create new expressions C++ has lots of expressions and expression operators Arithmetic : 1+3, 3-4, 5*6, 15/10, 15%10, 15/10.0 Variables : a, b, myvar, Fred, argv Logical : a&&b, a b (What do these equal if a=1 and b=0?) Relational : a<b, a>b, a==b, a!=b, a<b The Expression Parsing Problem: Write a program that evaluates arithmetic expressions For example: what does 43.2 / (100 + 5) evaluate to? We call such programs an Expression Evaluator Evaluating C++ expressions is a tricky problem! Reverse Polish Notation (RPN) or PostFix is much simpler! Wk02.1 Slide 2

3 PostFix Expressions C++ arithmetic expressions like 5+2 are in Infix notation That means that binary operators go in-between the operands PostFix Expressions place the operator after the operands So in PostFix, 5+2 is expressed as: 5 2 + As few simple examples: 1 2 + is 3, because it means 1+2 4 7 is -3, because it means 4-7 3 4 * is 12, because it means 3*4 8 4 / is 2, because it means 8/4 We will write a PostFix Expression Evaluator in C++ Wk02.1 Slide 3

4 Evaluating PostFix Expressions It gets more complex when there is more than one operator. How would we write the infix expression 1 + 2 * 3 in postfix? Since * is always evaluated before + with infix, we get this postfix expression: 2 3 * 1 + You evaluate starting at the left, and apply an operator to the two operands immediately proceeding it. 2 3 * 1 + 6 1 + 7 After evaluating an operator, you replace the numbers and operand with the new value. Wk02.1 Slide 4

5 More PostFix Example Expressions Now let s write the infix expression (1 + 2) * 3 in postfix This time + is evaluated before * because of the brackets The postfix expression is: 1 2 + 3 * It is evaluated in these steps: 1 2 + 3 * 3 3 * 9 The area of a circle π r 2 is written: pi * r * r in infix notation In postfix, it could be written as pi r * r * or r r * pi * Wk02.1 Slide 5

6 Stacks To evaluate a postfix expression, we need to introduce the idea of a stack, which is a simple data structure that lets us add and remove items at the top of the stack only. Pictorially, we ll draw a stack as a box with no top Here s an empty stack: Top of Stack Empty Stack Bottom of Stack Wk02.1 Slide 6

7 Pushing Items Onto a Stack Adding an element to a stack is called Pushing an element Function push() is used to push an element onto the stack For example: Here is what the stack looks like after we push 5 onto it: Top of Stack = 5 5 Bottom of Stack = 5 Wk02.1 Slide 7

8 Pushing Always Adds Elements to the Top After pushing 3 onto a stack already containing 5: Top of Stack = 3 3 5 Bottom of Stack = 5 Whenever you push an element, it becomes the new Top. Let s push 4: 4 3 5 Top of Stack = 4 Bottom of Stack = 5 Wk02.1 Slide 8

9 Popping Items from a Stack Can only remove the top element of a stack This is called popping the stack Use the function name pop() to pop the stack If we pop our stack then it looks like this: 4 3 5 pop() Top of Stack = 3 3 5 Bottom of Stack = 5 Pop removed 4 from the stack Wk02.1 Slide 9

10 Popping from an Empty Stack Popping the Stack again : 3 is removed Popping the Stack 3 rd time: 5 is removed, the stack is empty Popping an empty stack is an error! 3 pop() 5 5 pop() pop() Error! Empty Stack Wk02.1 Slide 10

11 Using a vector as a Stack Many different ways to implement a stack We will implement a stack using a vector vector was designed with stacks in mind! push_back and pop_back methods work like a stack Example: vector<int> stack; // initially empty stack.push_back(5); // push 5 stack.push_back(3); // push 3 stack.push_back(4); // push 4 cout <<"top of stack is " << stack.back(); // prints 4 stack.pop_back(); // 4 is popped stack.pop_back(); // 3 is popped stack.pop_back(); // 5 is popped Wk02.1 Slide 11

12 Stacks as a Vector A Stack is a data structure with three operations: push(x) puts x on the top of the stack pop() removes the top element of the stack peek() returns a copy of the top element without removing it Can treat stack as a vector and use any vector operation on it With stacks, normally when pop is called, we want to view the top element stack.pop_back() does not return the popped element all it does is delete the top of the stack so before calling pop_back we usually peek at the top using stack.back() Wk02.1 Slide 12

13 The Postfix Expression Evaluation Algorithm How do you evaluate the postfix expression 3 10 + 2 *? Here is the complete algorithm in pseudo-code: stack is initially empty for each token in the expression do: if token is a number then push it onto the stack else if token is "+" then pop the top 2 elements of the stack; call them a and b push a + b onto the stack else if token is "*" then pop the top 2 elements of the stack; call them a and b push a * b onto the stack else if token is "-" then pop the top 2 elements of the stack; call them a and b push a - b onto the stack else if token is "/" then pop the top 2 elements of the stack; call them a and b push a / b onto the stack end for Wk02.1 Slide 13

14 The Postfix Expression Evaluation Algorithm When this loop is done, the value of the expression is the number on the top of the stack A token is either a number (e.g. 10) or an operator (e.g. *) For example, the expression 3 10 + 2 * has 5 tokens: three operands and two operators stack is initially empty for each token in the expression do: if token is a number then push it onto the stack else if token is "+" then pop the top 2 elements of the stack; call them a and b push a + b onto the stack else if token is "*" then pop the top 2 elements of the stack; call them a and b push a * b onto the stack else if token is "-" then pop the top 2 elements of the stack; call them a and b push a - b onto the stack else if token is "/" then pop the top 2 elements of the stack; call them a and b push a / b onto the stack end for Wk02.1 Slide 14

15 A Traced Example Let s trace through the evaluation of expression: 3 9 + 2 * 3 is read: it is pushed onto the stack 9 is read: it is pushed onto the stack + is read, so 9 and 3 are popped, setting a = 3 and b = 9. Then a + b, which is 12, is pushed onto the stack 2 is read: it is pushed onto the stack * is read, so 2 and 12 are popped, setting a = 12 and b = 2 Then a * b, which is 24, is pushed onto the stack There are no more tokens, so the value of the postfix expression is the number on the top of the stack: 24 push(3) push(9) 9 token + push(2) 2 token * Empty Stack 3 3 pop() pop() push(3+9) 12 12 pop() pop() push(2*12) 24 Wk02.1 Slide 15

16 PostFix Practice What do each of the following postfix expressions evaluate to? Solutions: 6 2 17 1. 4 2 + 2. 4 2-3. 4 3 * 5 + 4. 4 3 + 5 * 5. 2 2 * 4 4 * + 4 / 35 5 Wk02.1 Slide 16

17 Writing a C++ Postfix Evaluator Now that we know how to evaluate postfix expressions, we are ready to write our program We will first try to get a simple working version of the algorithm up and running so we can start using it right away We will add features one at a time, testing them as we go Wk02.1 Slide 17

18 Postfix Evaluator Input The first thing is to be clear about the input to our program: numbers and operators are called tokens e.g. -8.886 is a token and / is a token a postfix expression is thus a sequence of 1 or more tokens e.g. the postfix expression 4 3 * 2 + consists of 5 tokens we will require that there be at least one space between each token so an expression like 4 3*2+ will cause an error in our evaluator Wk02.1 Slide 18

19 Reading Tokens Start by writing the basic code for reading tokens and distinguishing between numbers and operators: #include "error.h" #include <iostream> #include <string> using namespace std; string token; // global variable holds both operators and numbers int main() { cout << "Postfix expression evaluator\n"; while (cin >> token) { if (token=="+" token=="-" token=="*" token=="/") { cout << "'" << token << "' is an operator\n"; } else { cout << token << " is (perhaps) a number\n"; } } } Wk02.1 Slide 19

20 Adding a Stack We need to add a stack according to our pseudo-code Notice the algorithm never stores operators on the stack, only numbers Since we only ever store numbers on the stack, we can use a vector of doubles to represent our stack vector<double> stack; // global variable holds only numbers Wk02.1 Slide 20

21 Converting a string token to a double Each Token may be either an operator or a number So need to read tokens as strings Need to convert strings like "-3.05" to a double -3.05 Easiest way is to use C++11 function stod(): #include <string> string s = " -5.026 "; double x = stod(s); cout << "\"" << s << "\"" << "\n" << x << "\n"; This prints: " -5.026 " -5.026 Wk02.1 Slide 21

22 Evaluating the + Operator Now have enough to evaluate postfix expressions that use + string token; // global variable vector<double> stack; // global variable int main() { cout << "Postfix expression evaluator\n"; while (cin >> token) { if (token == "+") { // pop the top two elements of the stack // the top element is b, and the one under the top is a double b = stack.back(); stack.pop_back(); double a = stack.back(); stack.pop_back(); stack.push_back(a + b); // print the top of the stack so we can see the result cout << "tos = " << stack.back() << "\n"; } else { stack.push_back(string_to_double(token)); } } } Wk02.1 Slide 22

23 Sample Test Run for + Operator Test code available through CourSys: wk02.1_slide22 Sample output: (Keyboard input is Green) Postfix expression evaluator 1 2 + tos = 3 4 + tos = 7 3-1 -2 1 + tos = -1 <ctrl-d> RUN FINISHED; exit value 0; real time: 57s; user: 0ms; system: 0ms Wk02.1 Slide 23

24 Refactoring Repeated Code Sequences Create helper functions for code that gets repeated often Makes code easier to read, understand, and fix Notice always call stack.back() and stack.pop_back() together So it s a good candidate for a helper function to simplify things a bit Let s create a helper function to combine both operations into one // remove and return the element of the stack double pop() { double tos = stack.back(); stack.pop_back(); return tos; } For consistency, lets also simplify things with a similar push helper function: // put x on the top of the stack void push(double x) { stack.push_back(x); } Wk02.1 Slide 24

25 Postfix Evaluator Simplified with Helper Functions The code for the + operator is now shorter and easier to read! string token; // global variable vector<double> stack; // global variable int main() { cout << "Postfix expression evaluator\n"; while (cin >> token) { if (token == "+") { // pop the top two elements of the stack // the top element is b, and the one under the top is a double b = pop(); double a = pop(); push(a + b); // print the top of the stack so we can see the result cout << "tos = " << stack.back() << "\n"; } else { push(string_to_double(token)); } } } Wk02.1 Slide 25

26 Implementing the other Operators: - * / With + code working and simplified, time to code the other operators while (cin >> token) { if (token == "+") { // pop the top two elements of the stack // the top element is b, and the one under the top is a double b = pop(); double a = pop(); push(a + b); // print the top of the stack so we can see the result cout << "tos = " << stack.back() << "\n"; } else if (token == "-") { double b = pop(); double a = pop(); push(a - b); cout << "tos = " << stack.back() << "\n"; } else if (token == "*") { double b = pop(); double a = pop(); push(a * b); cout << "tos = " << stack.back() << "\n"; } else if (token == "/") { double b = pop(); double a = pop(); push(a / b); cout << "tos = " << stack.back() << "\n"; } else { } push(string_to_double(token)); Wk02.1 Slide 26

27 Testing the full version of the Postfix Evaluator Postfix expression evaluator 3 4 * tos = 12 1 2 + 3 4 + * tos = 3 tos = 7 tos = 21 <ctrl-d> RUN FINISHED; exit value 0; real time: 57s; user: 0ms; system: 0ms This version, Postfix_Eval_v3, works well enough. It took 60 lines of code to implement this postfix expression evaluator That s pretty good! Can we do better? Wk02.1 Slide 27

28 Adding more Features Lets add more features to our calculator right now we print the top of the stack after every operator that s useful for debugging but most of the time we usually only care about the final value of our calculation so let s replace the top-of-stack printing code with the =" operator the =" operator immediately prints the top of the stack let s add a user prompt --> let s also add a Q command to quit (hitting <ctrl>-d is not intuitive) Postfix expression evaluator --> 3 4 * = tos = 12 --> 1 2 + 3 4 + * = tos = 21 --> Q RUN FINISHED; exit value 0; real time: 57s; user: 0ms; system: 0ms Wk02.1 Slide 28

29 Printing the Top of the Stack To implement =, re-write the main if-else-if statement Eliminate the top-of-stack printing associated with each operator Add a check for the new = operator, and print the top-of-stack there if (token == "+") { double b = pop(); double a = pop(); push(a + b); } else if (token == "-") { double b = pop(); double a = pop(); push(a - b); } else if (token == "*") { double b = pop(); double a = pop(); push(a * b); } else if (token == "/") { double b = pop(); double a = pop(); push(a / b); } else if (token == =") { cout << "tos = " << stack.back() << "\n"; } else { push(string_to_double(token)); } Wk02.1 Slide 29

30 Adding the Q operator to exit the while loop while loops continue to loop until their boolean expression evaluates to false To support Q, this must become false when the Q Operator is found while ((cin >> token) && (token!= "Q")) { if (token == "+") { double b = pop(); double a = pop(); push(a + b); } else if (token == "-") { double b = pop(); double a = pop(); push(a - b); } else if (token == "*") { double b = pop(); double a = pop(); push(a * b); } else if (token == "/") { double b = pop(); double a = pop(); push(a / b); } else if (token == "=") { cout << "tos = " << stack.back() << "\n"; } else { push(string_to_double(token)); } } cout << "Bye!" << endl; Wk02.1 Slide 30

31 Adding an Input Prompt A useful feature is to display a text prompt for the user Need to make three small changes throughout the program: const string prompt = "--> "; int main() { cout << "Postfix expression evaluator\n"; cout << prompt; while ((cin >> token) && (token!= "Q")) { if (token == "+") { double b = pop(); double a = pop(); push(a + b); } //... code for -, *, and /... } else if (token == "=") { cout << "tos = " << stack.back() << "\n"; cout << prompt; } else { push(string_to_double(token)); } } cout << "Bye!" << endl; Wk02.1 Slide 31

32 Summary Key Things to take away from this presentation: While Global variables should be avoided, can be used to simplify complex code Stacks are very simple and very power data structures! Stacks can be implemented using C++ Vectors Helper Functions simplify main() and make the Flow of Control easier to read Boolean Expressions control when a while loop breaks out of the loop Wk02.1 Slide 32

33 References: 1. Walter Savitch, Problem Solving with C++. Pearson, 9th Edition, 2014, ISBN 978-0-13-359174-3 2. T.Donaldson, Parsing Postfix Expressions, http://www.cs.sfu.ca/coursecentral/135/tjd/postfix.html 3. B.Fraser, Install VMWare Player & Creating an Ubuntu VM (Part 1), https://youtu.be/txgrevxpbl4 4. B.Fraser, Configure a VMWare Player VM (Part 2), https://youtu.be/wvwsb5fh2fq 5. B.Fraser, Installing Netbeans for C++ on Ubuntu VM, https://youtu.be/46sdmxtwtsw Wk02.1 Slide 33

34 Time for Questions Wk02.1 Slide 34