n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

Similar documents
Abstract. Chapter 6 Writing a Program. Overview. Writing a program: Strategy. Building a program. Bjarne Stroustrup

Chapter 6 Writing a Program

Lecture 5: Writing a program

n Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CMPT 125 Assignment 2 Solutions

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

CS 11 C track: lecture 1

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

Python Programming: An Introduction to Computer Science

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

Overview Chapter 12 A display model

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

CS 111 Green: Program Design I Lecture 27: Speed (cont.); parting thoughts

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

1.2 Binomial Coefficients and Subsets

The number n of subintervals times the length h of subintervals gives length of interval (b-a).

CS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions

COP4020 Programming Languages. Compilers and Interpreters Prof. Robert van Engelen

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Running Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Python Programming: An Introduction to Computer Science

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Analysis of Algorithms

Morgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5

Exceptions. Your computer takes exception. The Exception Class. Causes of Exceptions

Numerical Methods Lecture 6 - Curve Fitting Techniques

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

Lecture 9: Exam I Review

Data Structures and Algorithms. Analysis of Algorithms

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Our Learning Problem, Again

Today s objectives. CSE401: Introduction to Compiler Construction. What is a compiler? Administrative Details. Why study compilers?

CS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016

One advantage that SONAR has over any other music-sequencing product I ve worked

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

. Written in factored form it is easy to see that the roots are 2, 2, i,

Location Steps and Paths

GE FUNDAMENTALS OF COMPUTING AND PROGRAMMING UNIT III

Administrative UNSUPERVISED LEARNING. Unsupervised learning. Supervised learning 11/25/13. Final project. No office hours today

Analysis of Algorithms

CS 111: Program Design I Lecture 15: Modules, Pandas again. Robert H. Sloan & Richard Warner University of Illinois at Chicago March 8, 2018

Creating Test Harnesses and Starter Applications

Learning to Shoot a Goal Lecture 8: Learning Models and Skills

CSE 417: Algorithms and Computational Complexity

Definitions. Error. A wrong decision made during software development

CS 111: Program Design I Lecture # 7: Web Crawler, Functions; Open Access

How do we evaluate algorithms?

Computational Geometry

From last week. Lecture 5. Outline. Principles of programming languages

Chapter 3. More Flow of Control. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CSE 111 Bio: Program Design I Lecture 17: software development, list methods

Chapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

The isoperimetric problem on the hypercube

Module 8-7: Pascal s Triangle and the Binomial Theorem

12-5A. Equivalent Fractions and Decimals. 1 Daily Common Core Review. Common Core. Lesson. Lesson Overview. Math Background

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

Which movie we can suggest to Anne?

CSE 111 Bio: Program Design I Class 11: loops

Polynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0

Solutions to Final COMS W4115 Programming Languages and Translators Monday, May 4, :10-5:25pm, 309 Havemeyer

CHAPTER IV: GRAPH THEORY. Section 1: Introduction to Graphs

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

CS 111: Program Design I Lecture 16: Module Review, Encodings, Lists

Examples and Applications of Binary Search

Arithmetic Sequences

Lecture 5. Counting Sort / Radix Sort

Workflow model GM AR. Gumpy. Dynagump. At a very high level, this is what gump does. We ll be looking at each of the items described here seperately.

Ones Assignment Method for Solving Traveling Salesman Problem

Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1

Counting the Number of Minimum Roman Dominating Functions of a Graph

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

prerequisites: 6.046, 6.041/2, ability to do proofs Randomized algorithms: make random choices during run. Main benefits:

Lecture 7 7 Refraction and Snell s Law Reading Assignment: Read Kipnis Chapter 4 Refraction of Light, Section III, IV

The VSS CCD photometry spreadsheet

CS 683: Advanced Design and Analysis of Algorithms

The Open University, Walton Hall, Milton Keynes, MK7 6AA First published 2004

15-859E: Advanced Algorithms CMU, Spring 2015 Lecture #2: Randomized MST and MST Verification January 14, 2015

Lecture 28: Data Link Layer

CS 111: Program Design I Lecture 20: Web crawling, HTML, Copyright

Pattern Recognition Systems Lab 1 Least Mean Squares

In this chapter, you learn the concepts and terminology of databases and

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

Extending The Sleuth Kit and its Underlying Model for Pooled Storage File System Forensic Analysis

It just came to me that I 8.2 GRAPHS AND CONVERGENCE

Lecture 5: Recursion. Recursion Overview. Recursion is a powerful technique for specifying funclons, sets, and programs

Major CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70

Transcription:

Overview Chapter 6 Writig a Program Bjare Stroustrup Some thoughts o software developmet The idea of a calculator Usig a grammar Expressio evaluatio Program orgaizatio www.stroustrup.com/programmig 3 Buildig a program 4 Aalysis Refie our uderstadig of the problem Desig Thik of the fial use of our program Create a overall structure for the program Implemetatio Write code Debug Test Go through these stages repeatedly 5 1

Writig a program: Strategy Programmig is also a practical still What is the problem to be solved? Is the problem statemet clear? Is the problem maageable, give the time, skills, ad tools available? Try breakig it ito maageable parts Do we kow of ay tools, libraries, etc. that might help? Yes, eve this early: iostreams, vector, etc. Build a small, limited versio solvig a key part of the problem To brig out problems i our uderstadig, ideas, or tools Possibly chage the details of the problem statemet to make it maageable If that does t work Throw away the first versio ad make aother limited versio Keep doig that util we fid a versio that we re happy with Build a full scale solutio Ideally by usig part of your iitial versio We lear by example Not by just seeig explaatios of priciples Not just by uderstadig programmig laguage rules The more ad the more varied examples the better You wo t get it right the first time You ca t lear to ride a bike from a correspodece course 6 7 Writig a program: Example I ll build a program i stages, makig lot of typical mistakes alog the way Eve experieced programmers make mistakes Lots of mistakes; it s a ecessary part of learig Desigig a good program is geuiely difficult It s ofte faster to let the compiler detect gross mistakes tha to try to get every detail right the first time Cocetrate o the importat desig choices Buildig a simple, icomplete versio allows us to experimet ad get feedback Good programs are grow A simple calculator Give expressios as iput from the keyboard, evaluate them ad write out the resultig value For example Expressio: 2+2 Result: 4 Expressio: 2+2*3 Result: 8 Expressio: 2+3-25/5 Result: 0 Let s refie this a bit more 8 9 2

Pseudo Code A simple calculator A first idea: it mai() variables while (get a lie) aalyze the expressio evaluate the expressio prit the result // pseudo code // what s a lie? // what does that mea? How do we represet 45+5/7 as data? How do we fid 45 + 5 / ad 7 i a iput strig? How do we make sure that 45+5/7 meas 45+(5/7) rather tha (45+5)/7? Should we allow floatig-poit umbers (sure!) Ca we have variables? v=7; m=9; v*m (later) 10 Wait! We are just about to reivet the wheel! Read Chapter 6 for more examples of dead-ed approaches What would the experts do? Computers have bee evaluatig expressios for 50+ years There has to be a solutio! What did the experts do? Readig is good for you Askig more experieced frieds/colleagues ca be far more effective, pleasat, ad time-effective tha sloggig alog o your ow Do t re-ivet the wheel 11 Expressio Grammar This is what the experts usually do write a grammar: Expressio : Term Expressio + Term e.g., 1+2, (1-2)+3, 2*3+1 Expressio - Term Term : Primary Term * Primary e.g., 1*2, (1-2)*3.5 Term / Primary Term % Primary Primary : Number e.g., 1, 3.5 ( Expressio ) e.g., (1+2*3) Number : floatig-poit literal e.g., 3.14, 0.274e1, or 42 as defied for C++ A program is built out of Tokes (e.g., umbers ad operators). 12 A side trip: Grammars What s a grammar? A set of (sytax) rules for expressios. The rules say how to aalyze ( parse ) a expressio. Some rules seem hard-wired ito our brais Example, you kow what this meas: 2*3+4/2 birds fly but fish swim You kow that this is wrog: 2 * + 3 4/2 fly birds fish but swim How ca we teach what we kow to a computer? Why is it right/wrog? How do we kow? 13 3

Grammars Eglish Grammars - expressio 14 15 Grammars - expressio Grammars - expressio 16 17 4

Fuctios for parsig Fuctio Retur Types We eed fuctios to match the grammar rules get() // read characters ad compose tokes // calls ci for iput expressio() // deal with + ad // calls term() ad get() term() // deal with *, /, ad % // calls primary() ad get() primary() // deal with umbers ad paretheses // calls expressio() ad get() Note: each fuctio deals with a specific part of a expressio ad leaves everythig else to other fuctios this radically simplifies each fuctio. Aalogy: a group of people ca deal with a complex problem by each perso hadlig oly problems i his/her ow specialty, leavig the rest for colleagues. 18 What should the parser fuctios retur? How about the result? Toke get_toke(); // read characters ad compose tokes double expressio(); // deal with + ad // retur the sum (or differece) double term(); // deal with *, /, ad % // retur the product (or ) double primary(); // deal with umbers ad paretheses // retur the value What is a Toke? 19 umber 4.5 What is a toke? + Dealig with + ad - We wat to see iput as a stream of tokes We read characters 1 + 4*(4.5-6) (That s 13 characters icl. 2 spaces) 9 tokes i that expressio: 1 + 4 * ( 4.5-6 ) 6 kids of tokes i that expressio: umber + * ( - ) We wat each toke to have two parts A kid ; e.g., umber A value; e.g., 4 We eed a type to represet this Toke idea We ll build that i the ext lecture, but for ow: get_toke() gives us the ext toke from iput t.kid gives us the kid of the toke t.value gives us the value of the toke 20 Expressio: Term Expressio '+' Term Expressio '-' Term // Note: every Expressio starts with a Term double expressio() // read ad evaluate: 1 1+2.5 1+2+3.14 etc. double left = term(); // get the Term while (true) Toke t = get_toke(); // get the ext toke switch (t.kid) // ad do the right thig with it case '+': left += term(); break; case '-': left -= term(); break; default: retur left; // retur the value of the expressio 21 5

Dealig with *, /, ad % Dealig with * ad / double term() // exactly like expressio(), but for *, /, ad % double left = primary(); // get the Primary while (true) Toke t = get_toke(); // get the ext Toke switch (t.kid) case '*': left *= primary(); break; case '/': left /= primary(); break; case '%': left %= primary(); break; default: retur left; // retur the value Oops: does t compile % is t defied for floatig-poit umbers 22 Term : Primary Term * Primary Term / Primary // Note: every Term starts with a Primary double term() // exactly like expressio(), but for *, ad / double left = primary(); // get the Primary while (true) Toke t = get_toke(); // get the ext Toke switch (t.kid) case '*': left *= primary(); break; case '/': left /= primary(); break; default: retur left; // retur the value 23 Dealig with divide by 0 double term() // exactly like expressio(), but for * ad / double left = primary(); // get the Primary while (true) Toke t = get_toke(); // get the ext Toke switch (t.kid) case '*': left *= primary(); break; case '/': double d = primary(); if (d==0) error("divide by zero"); left /= d; break; default: retur left; // retur the value 24 Dealig with umbers ad paretheses double primary() // Number or ( Expressio ) Toke t = get_toke(); switch (t.kid) case '(': // hadle ( expressio ) double d = expressio(); t = get_toke(); if (t.kid!= ')') error("')' expected"); retur d; case '8': // we use 8 to represet the kid of a umber retur t.value; // retur the umber s value default: error("primary expected"); 25 6

Program orgaizatio The program Toke get_toke() error() #iclude "std_lib_facilities.h" // Toke stuff (explaied i the ext lecture) primary() double expressio(); // declaratio so that primary() ca call expressio() istream ci >> term() double primary() /* */ // deal with umbers ad paretheses double term() /* */ // deal with * ad / (pity about %) double expressio() /* */ // deal with + ad ostream cout << mai() expressio() it mai() /* */ // o ext slide Who calls whom? (ote the loop) 26 27 The program mai() A mystery it mai() try while (ci) cout << expressio() << '\'; keep_widow_ope(); // for some Widows versios catch (rutime_error& e) cerr << e.what() << edl; keep_widow_ope (); retur 1; catch ( ) cerr << "exceptio \"; keep_widow_ope (); retur 2; 28 2 3 4 2 a aswer 5+6 5 a aswer X Bad toke a aswer (fially, a expected aswer) 29 7

Expect mysteries A mystery Your first try rarely works as expected That s ormal ad to be expected Eve for experieced programmers If it looks as if it works be suspicious Ad test a bit more Now comes the debuggig Fidig out why the program misbehaves Ad do t expect your secod try to work either 1 2 3 4+5 6+7 8+9 10 11 12 1 a aswer 4 a aswer 6 a aswer 8 a aswer 10 a aswer A mystery Aha! Our program eats two out of three iputs How come? Let s have a look at expressio() 30 31 Dealig with + ad - Dealig with + ad - Expressio: Term Expressio + Term Expressio - Term // Note: every Expressio starts with a Term double expressio() // read ad evaluate: 1 1+2.5 1+2+3.14 etc. double left = term(); // get the Term while (true) Toke t = get_toke(); // get the ext toke switch (t.kid) // ad do the right thig with it case '+': left += term(); break; case '-': left -= term(); break; default: retur left; // <<< does t use ext toke 32 So, we eed a way to put back a toke! Put back ito what? the iput, of course: we eed a iput stream of tokes, a toke stream double expressio() // deal with + ad - double left = term(); while (true) Toke t = ts.get(); // get the ext toke from a toke stream switch (t.kid) case '+': left += term(); break; case '-': left -= term(); break; default: ts.putback(t); // put the uused toke back retur left; 33 8

Dealig with * ad / Now make the same chage to term() double term() // deal with * ad / double left = primary(); while (true) Toke t = ts.get(); // get the ext Toke from iput switch (t.kid) case '*': // deal with * case '/': // deal with / default: ts.putback(t); // put uused toke back ito iput stream retur left; 34 It sort of works The program That s ot bad for a first try Well, secod try Well, really, the fourth try; see the book But sort of works is ot good eough Whe the program sort of works is whe the work (ad fu) really start Now we ca get feedback! 35 Aother mystery The mai() program 2 3 4 2+3 2*3 2 a aswer 3 a aswer 4 a aswer 5 a aswer What! No 6? The program looks ahead oe toke It s waitig for the user So, we itroduce a prit result commad While we re at it, we also itroduce a quit commad it mai() double val = 0; while (ci) Toke t = ts.get(); // rather tha get_toke() if (t.kid == 'q') break; // q for quit if (t.kid == ';') // ; for prit ow cout << val << '\'; // prit result else ts. putback(t); // put a toke back ito the iput stream val = expressio(); // evaluate keep_widow_ope(); // exceptio hadlig 36 37 9

Now the calculator is miimally useful 2; 2 a aswer 2+3; 5 a aswer 3+4*5; 23 a aswer q Next lecture Completig a program Tokes Recoverig from errors Cleaig up the code Code review Testig 38 39 10