{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Chapter 6

# whats what does that mean what how do we represent

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 45+5/7 as data? ow 45+5/7 How do we find 45 + 5 / and 7 in an input string? ow and How do we make sure that 45+5/7 means 45+(5/7) rather than (45+5)/7? How 45+5/7 45+(5/7) (45+5)/7 Should we allow floating-point numbers (sure!) Can we have variables? v=7; m=9; v*m (later) an v=7; Stroustrup/Programming 8 A simple calculator simple Wait! We are just about to reinvent the wheel! Read Chapter 6 for more examples of dead-end approaches What would the experts do? Computers have been evaluating expressions for 50+ years There has to be a solution! There has What did the experts do? What did Reading is good for you Asking more experienced friends/colleagues can be far more Asking effective, pleasant, and time-effective than slogging along on your own own Stroustrup/Programming 9 Expression Grammar Expression This is what the experts usually do – write a grammar: This grammar Expression : Term Expression ‘+’ Term Expression Expression ‘-’ Term Term : Primary Term ‘*’ Primary Term Term ‘/’ Primary Term ‘%’ Primary e.g., 1+2, (1-2)+3, 2*3+1 e.g. 1+2 e.g., 1*2, (1-2)*3.5 e.g. 1*2 (1-2)*3.5 Primary : Number ‘(‘ Expression ‘)’ e.g., 1, 3.5 e.g. 3.5 e.g., (1+2*3) (1+2*3) Number : floating-point literal e.g., 3.14, 0.274e1, or 42 – as defined for C++ 3.14 0.274e1 or as A program is built out of Tokens (e.g., numbers and operators). Stroustrup/Programming 10 A side trip: Grammars side What’s a grammar? What’s grammar A set of (syntax) rules for expressions. The rules say how to analyze (“parse”) an expression. Some seem hard-wired into our brains Example, you know what this means: You know that this is wrong: 2*3+4/2 birds fly but fish swim 2 * + 3 4/2 fly birds fish but swim Why is it right/wrong? How do we know? How can we teach what we know to a computer? Stroustrup/Programming 11 Grammars – “English” Grammars Stroustrup/Programming 12 Grammars - expression Grammars Stroustrup/Programming 13 Grammars - expression Grammars Stroustrup/Programming 14 Grammars - expression Grammars Stroustrup/Programming 15 Functions for parsing Functions We need functions to match the grammar rules get() // read characters and compose tokens read // calls cin for input cin expression() // deal with + and – deal // calls term() and get() and term () // deal with *, /, and % deal // calls primary() and get() and primary() // deal with numbers and parentheses deal // calls expression() and get() and 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...
View Full Document

{[ snackBarMessage ]}