Chapter 6 Writing a Program Bjarne Stroustrup www.stroustrup.com/Programming.

Slides:



Advertisements
Similar presentations
Chapter 5 Errors Bjarne Stroustrup
Advertisements

Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Chapter 4 Computation Bjarne Stroustrup
Chapter 6 Writing a Program
MATH 224 – Discrete Mathematics
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 7: Errors 1 Based on slides created by Bjarne Stroustrup.
Chapter 7 Completing a Program John Keyser’s Modification of Slides by Bjarne Stroustrup
Errors Lecture 6 Hartmut Kaiser
Debugging Introduction to Computing Science and Programming I.
CS 330 Programming Languages 09 / 13 / 2007 Instructor: Michael Eckmann.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
 Monday, 9/30/02, Slide #1 CS106 Introduction to CS1 Monday, 9/30/02  QUESTIONS (on HW02, etc.)??  Today: Libraries, program design  More on Functions!
Computer Science 1620 Programming & Problem Solving.
Complexity (Running Time)
CS 280 Data Structures Professor John Peterson. Lexer Project Questions? Must be in by Friday – solutions will be posted after class The next project.
28-Jun-15 Recognizers. 2 Parsers and recognizers Given a grammar (say, in BNF) and a string, A recognizer will tell whether the string belongs to the.
CSCE 121: Introduction to Program Design and Concepts Dr. J
Programming is instructing a computer to perform a task for you with the help of a programming language.
Copyright 2003 Scott/Jones Publishing Brief Version of Starting Out with C++, 4th Edition Chapter 1 Introduction to Computers and Programming.
Grammars and Parsing. Sentence  Noun Verb Noun Noun  boys Noun  girls Noun  dogs Verb  like Verb  see Grammars Grammar: set of rules for generating.
PRINCIPLES OF PROGRAMMING Revision. A Computer  A useful tool for solving a great variety of problems.  To make a computer do anything (i.e. solve.
Lecture 4 Errors Bjarne Stroustrup
Chapter 5: Control Structures II (Repetition)
Organizing Programs and Data Lecture 5 Hartmut Kaiser
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 5 Errors Hartmut Kaiser
General Programming Introduction to Computing Science and Programming I.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #002 (January 17, 2015)
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
Chapter 6 Writing a Program John Keyser’s Modification of Slides by Bjarne Stroustrup
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Profs. Necula CS 164 Lecture Top-Down Parsing ICOM 4036 Lecture 5.
Lesson 3 CDT301 – Compiler Theory, Spring 2011 Teacher: Linus Källberg.
1 Problem Solving with C++ The Object of Programming Walter Savitch Chapter 1 Introduction to Computers and C++ Programming Slides by David B. Teague,
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
File I/O ifstreams and ofstreams Sections 11.1 &
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
CSE 332: C++ execution control statements Overview of C++ Execution Control Expressions vs. statements Arithmetic operators and expressions * / % + - Relational.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
Looping and Counting Lecture 3 Hartmut Kaiser
Chapter 05 (Part III) Control Statements: Part II.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 6 Writing a Program Hartmut Kaiser
1 Debugging and Syntax Errors in C++. 2 Debugging – a process of finding and fixing bugs (errors or mistakes) in a computer program.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 7 Completing a Program Hartmut Kaiser
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
1 10/3/05CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
Fundamental Programming Fundamental Programming More Expressions and Data Types.
Efficiently Solving Computer Programming Problems Doncho Minkov Telerik Corporation Technical Trainer.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 6: Stepwise refinement revisited, Midterm review.
Loop Design What goes into coding a loop. Considerations for Loop Design ● There are basically two kinds of loops: ● Those that form some accumulated.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Introduction to Parsing (adapted from CS 164 at Berkeley)
Bjarne Stroustrup Chapter 5 Errors Bjarne Stroustrup
Introduction to C++ Programming
Chapter 3: Input/Output
Chapter 7 Completing a Program
By Hector M Lugo-Cordero September 3, 2008
Chapter 7 Completing a Program
Engineering Problem Solving with C++ An Object Based Approach
The Recursive Descent Algorithm
LCC 6310 Computation as an Expressive Medium
Chapter 7 Completing a Program
Presentation transcript:

Chapter 6 Writing a Program Bjarne Stroustrup

Abstract This lecture and the next describe the process of designing a program through the example of a simple “desk calculator.” This lecture and the next describe the process of designing a program through the example of a simple “desk calculator.” 2Stroustrup/Programming/2015

Overview Some thoughts on software development Some thoughts on software development The idea of a calculator The idea of a calculator Using a grammar Using a grammar Expression evaluation Expression evaluation Program organization Program organization 3Stroustrup/Programming/2015

4

Building a program Analysis Analysis Refine our understanding of the problem Refine our understanding of the problem Think of the final use of our program Think of the final use of our program Design Design Create an overall structure for the program Create an overall structure for the program Implementation Implementation Write code Write code Debug Debug Test Test Go through these stages repeatedly Go through these stages repeatedly 5Stroustrup/Programming/2015

Writing a program: Strategy What is the problem to be solved? What is the problem to be solved? Is the problem statement clear? Is the problem statement clear? Is the problem manageable, given the time, skills, and tools available? Is the problem manageable, given the time, skills, and tools available? Try breaking it into manageable parts Try breaking it into manageable parts Do we know of any tools, libraries, etc. that might help? Do we know of any tools, libraries, etc. that might help? Yes, even this early: iostreams, vector, etc. Yes, even this early: iostreams, vector, etc. Build a small, limited version solving a key part of the problem Build a small, limited version solving a key part of the problem To bring out problems in our understanding, ideas, or tools To bring out problems in our understanding, ideas, or tools Possibly change the details of the problem statement to make it manageable Possibly change the details of the problem statement to make it manageable If that doesn’t work If that doesn’t work Throw away the first version and make another limited version Throw away the first version and make another limited version Keep doing that until we find a version that we’re happy with Keep doing that until we find a version that we’re happy with Build a full scale solution Build a full scale solution Ideally by using part of your initial version Ideally by using part of your initial version 6Stroustrup/Programming/2015

Programming is also a practical still We learn by example We learn by example Not by just seeing explanations of principles Not by just seeing explanations of principles Not just by understanding programming language rules Not just by understanding programming language rules The more and the more varied examples the better The more and the more varied examples the better You won’t get it right the first time You won’t get it right the first time “You can’t learn to ride a bike from a correspondence course” “You can’t learn to ride a bike from a correspondence course” Stroustrup/Programming/2015 7

Writing a program: Example I’ll build a program in stages, making lot of “typical mistakes” along the way I’ll build a program in stages, making lot of “typical mistakes” along the way Even experienced programmers make mistakes Even experienced programmers make mistakes Lots of mistakes; it’s a necessary part of learning Lots of mistakes; it’s a necessary part of learning Designing a good program is genuinely difficult Designing a good program is genuinely difficult It’s often faster to let the compiler detect gross mistakes than to try to get every detail right the first time It’s often faster to let the compiler detect gross mistakes than to try to get every detail right the first time Concentrate on the important design choices Concentrate on the important design choices Building a simple, incomplete version allows us to experiment and get feedback Building a simple, incomplete version allows us to experiment and get feedback Good programs are “grown” Good programs are “grown” 8Stroustrup/Programming/2015

A simple calculator Given expressions as input from the keyboard, evaluate them and write out the resulting value Given expressions as input from the keyboard, evaluate them and write out the resulting value For example For example Expression: 2+2 Expression: 2+2 Result: 4 Result: 4 Expression: 2+2*3 Expression: 2+2*3 Result: 8 Result: 8 Expression: /5 Expression: /5 Result: 0 Result: 0 Let’s refine this a bit more … Let’s refine this a bit more … 9Stroustrup/Programming/2015

Pseudo Code A first idea: A first idea: int main() { variables// pseudo code while (get a line) {// what’s a line? analyze the expression// what does that mean? evaluate the expression print the result }} How do we represent 45+5/7 as data? How do we represent 45+5/7 as data? How do we find / and 7 in an input string? How do we find / and 7 in an input string? How do we make sure that 45+5/7 means 45+(5/7) rather than (45+5)/7? How do we make sure that 45+5/7 means 45+(5/7) rather than (45+5)/7? Should we allow floating-point numbers (sure!) Should we allow floating-point numbers (sure!) Can we have variables? v=7; m=9; v*m (later) Can we have variables? v=7; m=9; v*m (later) 10Stroustrup/Programming/2015

A simple calculator Wait! Wait! We are just about to reinvent the wheel! We are just about to reinvent the wheel! Read Chapter 6 for more examples of dead-end approaches Read Chapter 6 for more examples of dead-end approaches What would the experts do? What would the experts do? Computers have been evaluating expressions for 50+ years Computers have been evaluating expressions for 50+ years There has to be a solution! There has to be a solution! What did the experts do? What did the experts do? Reading is good for you Reading is good for you Asking more experienced friends/colleagues can be far more effective, pleasant, and time-effective than slogging along on your own Asking more experienced friends/colleagues can be far more effective, pleasant, and time-effective than slogging along on your own “Don’t re-invent the wheel” “Don’t re-invent the wheel” 11Stroustrup/Programming/2015

Expression Grammar This is what the experts usually do – write a grammar: This is what the experts usually do – write a grammar: Expression : Term Expression ‘+’ Term e.g., 1+2, (1-2)+3, 2*3+1 Expression ‘-’ Term Term : Primary Term ‘*’ Primary e.g., 1*2, (1-2)*3.5 Term ‘/’ Primary Term ‘%’ Primary Primary : Number e.g., 1, 3.5 ‘(‘ Expression ‘)’e.g., (1+2*3) Number : floating-point literale.g., 3.14, 0.274e1, or 42 – as defined for C++ A program is built out of Tokens (e.g., numbers and operators). 12Stroustrup/Programming/2015

A side trip: Grammars What’s a grammar? What’s a grammar? A set of (syntax) rules for expressions. A set of (syntax) rules for expressions. The rules say how to analyze (“parse”) an expression. The rules say how to analyze (“parse”) an expression. Some rules seem hard-wired into our brains Some rules seem hard-wired into our brains Example, you know what this means: Example, you know what this means: 2*3+4/2 2*3+4/2 birds fly but fish swim birds fly but fish swim You know that this is wrong: You know that this is wrong: 2 * + 3 4/2 2 * + 3 4/2 fly birds fish but swim fly birds fish but swim How can we teach what we know to a computer? How can we teach what we know to a computer? Why is it right/wrong? Why is it right/wrong? How do we know? How do we know? 13Stroustrup/Programming/2015

Grammars – “English” 14Stroustrup/Programming/2015

Grammars - expression 15Stroustrup/Programming/2015

Grammars - expression 16Stroustrup/Programming/2015

Grammars - expression 17Stroustrup/Programming/2015

Functions for parsing We need functions to match the grammar rules get()// read characters and compose tokens // calls cin for input expression()// deal with + and – // calls term() and get() term()// deal with *, /, and % // calls primary() and get() primary()// deal with numbers and parentheses // calls expression() and get() Note: each function deals with a specific part of an expression and leaves everything else to other functions – this radically simplifies each function. Analogy: a group of people can deal with a complex problem by each person handling only problems in his/her own specialty, leaving the rest for colleagues. 18Stroustrup/Programming/2015

Function Return Types What should the parser functions return? What should the parser functions return? How about the result? How about the result? Token get_token();// read characters and compose tokens double expression();// deal with + and – // return the sum (or difference) double term();// deal with *, /, and % // return the product (or …) double primary();// deal with numbers and parentheses //return the value What is a Token? What is a Token? 19Stroustrup/Programming/2015

What is a token? We want to see input as a stream of tokens We want to see input as a stream of tokens We read characters 1 + 4*(4.5-6) (That’s 13 characters incl. 2 spaces) We read characters 1 + 4*(4.5-6) (That’s 13 characters incl. 2 spaces) 9 tokens in that expression: * ( ) 9 tokens in that expression: * ( ) 6 kinds of tokens in that expression: number + * ( - ) 6 kinds of tokens in that expression: number + * ( - ) We want each token to have two parts We want each token to have two parts A “kind”; e.g., number A “kind”; e.g., number A value; e.g., 4 A value; e.g., 4 We need a type to represent this “Token” idea We need a type to represent this “Token” idea We’ll build that in the next lecture, but for now: We’ll build that in the next lecture, but for now: get_token() gives us the next token from input get_token() gives us the next token from input t.kind gives us the kind of the token t.kind gives us the kind of the token t.value gives us the value of the token t.value gives us the value of the token 20 + number 4.5 Stroustrup/Programming/2015

Dealing with + and - Expression:Term Expression '+' Term// Note: every Expression starts with a Term Expression '-' Term double expression()// read and evaluate: etc. { double left = term(); // get the Term while (true) { Token t = get_token();// get the next token… switch (t.kind) {// … and do the right thing with it case '+': left += term(); break; case '-': left -= term(); break; default: return left;// return the value of the expression }}} 21Stroustrup/Programming/2015

Dealing with *, /, and % double term()// exactly like expression(), but for *, /, and % { double left = primary(); // get the Primary while (true) { Token t = get_token();// get the next Token… switch (t.kind) { case '*': left *= primary(); break; case '/': left /= primary(); break; case '%': left %= primary(); break; default: return left;// return the value }}} Oops: doesn’t compile Oops: doesn’t compile % isn’t defined for floating-point numbers % isn’t defined for floating-point numbers 22Stroustrup/Programming/2015

Dealing with * and / Term : Primary Term ‘*’ Primary // Note: every Term starts with a Primary Term ‘/’ Primary double term()// exactly like expression(), but for *, and / { double left = primary(); // get the Primary while (true) { Token t = get_token();// get the next Token switch (t.kind) { case '*': left *= primary(); break; case '/': left /= primary(); break; default: return left;// return the value }}} 23Stroustrup/Programming/2015

Dealing with divide by 0 double term()// exactly like expression(), but for * and / { double left = primary(); // get the Primary while (true) { Token t = get_token();// get the next Token switch (t.kind) { case '*': left *= primary(); break; case '/': {double d = primary(); {double d = primary(); if (d==0) error("divide by zero"); left /= d; break; }default: return left;// return the value }}} 24Stroustrup/Programming/2015

Dealing with numbers and parentheses double primary()// Number or ‘(‘ Expression ‘)’ double primary()// Number or ‘(‘ Expression ‘)’{ Token t = get_token(); switch (t.kind) { case '(': // handle ‘(’expression ‘)’ {double d = expression(); {double d = expression(); t = get_token(); if (t.kind != ')') error("')' expected"); return d; } case '8':// we use ‘8’ to represent the “kind” of a number return t.value;// return the number’s value default: error("primary expected"); }} 25Stroustrup/Programming/2015

Program organization Who calls whom? (note the loop) Who calls whom? (note the loop) 26 primary() expression() term() main() istream cin >> error() Token ostream cout << get_token() Stroustrup/Programming/2015

The program #include "std_lib_facilities.h" // Token stuff (explained in the next lecture) double expression(); // declaration so that primary() can call expression() double primary() { /* … */ }// deal with numbers and parentheses double term() { /* … */ }// deal with * and / (pity about %) double expression() { /* … */ }// deal with + and – int main() { /* … */ }// on next slide 27Stroustrup/Programming/2015

The program – main() int main() try { while (cin) cout << expression() << '\n'; cout << expression() << '\n'; keep_window_open();// for some Windows versions } catch (runtime_error& e) { cerr << e.what() << endl; keep_window_open (); return 1; } catch (…) { cerr << "exception \n"; keep_window_open (); return 2; } 28Stroustrup/Programming/2015

A mystery an answer 2an answer an answer 5an answer X Bad tokenan answer (finally, an expected answer) Bad tokenan answer (finally, an expected answer) 29Stroustrup/Programming/2015

A mystery Expect “mysteries” Expect “mysteries” Your first try rarely works as expected Your first try rarely works as expected That’s normal and to be expected That’s normal and to be expected Even for experienced programmers Even for experienced programmers If it looks as if it works be suspicious If it looks as if it works be suspicious And test a bit more And test a bit more Now comes the debugging Now comes the debugging Finding out why the program misbehaves Finding out why the program misbehaves And don’t expect your second try to work either And don’t expect your second try to work either Stroustrup/Programming/

A mystery an answer 1an answer 4an answer 4an answer 6an answer 6an answer 8an answer 8an answer 10an answer 10an answer Aha! Our program “eats” two out of three inputs Aha! Our program “eats” two out of three inputs How come? How come? Let’s have a look at expression() Let’s have a look at expression() 31Stroustrup/Programming/2015

Dealing with + and - Expression:Term Expression ‘+’ Term// Note: every Expression starts with a Term Expression ‘-’ Term double expression()// read and evaluate: etc. { double left = term(); // get the Term while (true) { Token t = get_token();// get the next token… switch (t.kind) {// … and do the right thing with it case '+': left += term(); break; case '-': left -= term(); break; default: return left;// <<< doesn’t use “next token” }}} 32Stroustrup/Programming/2015

Dealing with + and - So, we need a way to “put back” a token! So, we need a way to “put back” a token! Put back into what? Put back into what? “the input,” of course: we need an input stream of tokens, a “token stream” “the input,” of course: we need an input stream of tokens, a “token stream” double expression()// deal with + and - { double left = term(); while (true) { Token t = ts.get(); // get the next token from a “token stream” switch (t.kind) { case '+': left += term(); break; case '-': left -= term(); break; default: ts.putback(t); // put the unused token back return left; return left;}}} 33Stroustrup/Programming/2015

Dealing with * and / Now make the same change to term() Now make the same change to term() double term()// deal with * and / { double left = primary(); while (true) { Token t = ts.get();// get the next Token from input switch (t.kind) { case '*': // deal with * case '/': // deal with / default: ts.putback(t);// put unused token back into input stream return left; }}} 34Stroustrup/Programming/2015

The program It “sort of works” It “sort of works” That’s not bad for a first try That’s not bad for a first try Well, second try Well, second try Well, really, the fourth try; see the book Well, really, the fourth try; see the book But “sort of works” is not good enough But “sort of works” is not good enough When the program “sort of works” is when the work (and fun) really start When the program “sort of works” is when the work (and fun) really start Now we can get feedback! Now we can get feedback! 35Stroustrup/Programming/2015

Another mystery * *3 2an answer 2an answer 3an answer 3an answer 4an answer 4an answer 5an answer 5an answer What! No “6” ? What! No “6” ? The program looks ahead one token The program looks ahead one token It’s waiting for the user It’s waiting for the user So, we introduce a “print result” command So, we introduce a “print result” command While we’re at it, we also introduce a “quit” command While we’re at it, we also introduce a “quit” command 36Stroustrup/Programming/2015

The main() program int main() { double val = 0; while (cin) { Token t = ts.get();// rather than get_token() if (t.kind == 'q') break;// ‘q’ for “quit” if (t.kind == ';')// ‘;’ for “print now” cout << val << '\n';// print result else ts. putback (t);// put a token back into the input stream val = expression();// evaluate }keep_window_open();} // … exception handling … 37Stroustrup/Programming/2015

Now the calculator is minimally useful 2; 2; 2an answer 2an answer 2+3; 2+3; 5an answer 5an answer 3+4*5; 3+4*5; 23an answer 23an answer q 38Stroustrup/Programming/2015

Next lecture Completing a program Completing a program Tokens Tokens Recovering from errors Recovering from errors Cleaning up the code Cleaning up the code Code review Code review Testing Testing 39Stroustrup/Programming/2015