Chapter 4 - Chapter 4 Chapter Computation Bjarne Stroustrup

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

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 4 Chapter Computation Bjarne Stroustrup www.stroustrup.com/Programming Abstract Today, I’ll present the basics of computation. In Today, particular, we’ll discuss expressions, how to iterate over a series of values (“iteration”), and select between two alternative actions (“selection”). I’ll also show how a particular sub(“selection”). computation can be named and specified computation separately as a function. To be able to perform more realistic computations, I will introduce the vector type to hold sequences of values. vector type Selection, Iteration, Function, Vector Stroustrup/Programming 2 Overview Computation What is computable? How best to compute it? Abstractions, algorithms, heuristics, data structures Language constructs and ideas Sequential order of execution Expressions and Statements Selection Selection Iteration Functions Functions Vectors Stroustrup/Programming 3 You already know most of this Note: You know how to do arithmetic You d = a+b*c You know how to select “if this is true, do that; otherwise do something else ” You know how to “iterate” You know how to do functions “do this until you are finished” “do that 100 times” “go ask Joe and bring back the answer” “hey Joe, calculate this for me and send me the answer” What I will show you today is mostly just vocabulary and What syntax for what you already know syntax Stroustrup/Programming 4 Computation Code, often messy, (input) data often a lot of code (output) data data Input: from keyboard, files, other input devices, other programs, other Input: parts of a program parts Computation – what our program will do with the input to produce the Computation output. output. Output: to screen, files, other output devices, other programs, other parts Output: of a program of Stroustrup/Programming 5 Computation Our job is to express computations One tool is called Divide and Conquer Provide a higher-level concept that hides detail Organization of data is often the key to good code to break up big computations into many little ones Another tool is Abstraction Correctly Simply Efficiently Input/output formats Protocols Data structures Note the emphasis on structure and organization You don’t get good code just by writing a lot of statements Stroustrup/Programming 6 Language features Each programming language feature exists to express Each a fundamental idea fundamental For example + : addition addition * : multiplication multiplication if (expression) statement else statement ; selection else while (expression) statement ; iteration iteration f(x); function/operation f(x); function/operation … We combine language features to create programs Stroustrup/Programming 7 Expressions // compute area: // compute int length = 20; / / the simplest expression: a literal (here, 20) the // (here used to initialize a variable) // (here int width = 40; int area = length*width; int average = (length+width)/2; // a multiplication // multiplication // addition and division addition The usual rules of precedence apply: a*b+c/d means (a*b)+(c/d) and not a*(b+c)/d. (a*b)+(c/d) a*(b+c)/d If in doubt, parenthesize. If complicated, parenthesize. Don’t write “absurdly complicated” expressions: a*b+c/d*(e-f/g)/h+7 // too complicated // too Choose meaningful names. Stroustrup/Programming 8 Expressions Expressions are made out of operators and operands Operators specify what is to be done Operands specify the data for the operators to work with Boolean type: bool (true and false) Boolean true and Equality operators: = = (equal), != (not equal) != Logical operators: && (and), || (or), ! (not) Logical && || (not) Relational operators: < (less than), > (greater than), <=, >= Relational <= >= Character type: char (e.g., 'a', '7', and '@') Character char (e.g., 'a' and '@' Integer types: short, int, long Integer short, arithmetic operators: +, -, *, /, % (remainder) +, Floating-point types: e.g., float, double (e.g., 12.45 and 1.234e3) Floating-point float, (e.g., and arithmetic operators: +, -, *, / arithmetic +, Stroustrup/Programming 9 Concise Operators For many binary operators, there are (roughly) equivalent For more concise operators more For example a += c means a = a+c += means a *= scale means a = a*scale *= means ++a means a += 1 ++a means or a = a+1 or a+1 “Concise operators” are generally better to use (clearer, express an idea more directly) Stroustrup/Programming 10 10 Statements A statement is For example an expression followed by a semicolon, or a declaration, or a “control statement” that determines the flow of control a = b; double d2 = 2.5; if (x == 2) y = 4; while (cin >> number) numbers.push_back(number); int average = (length+width)/2; return x; You may not understand all of these just now, but you will … Stroustrup/Programming 11 11 Selection Sometimes we must select between alternatives For example, suppose we want to identify the larger of two For values. We can do this with an if statement if if (a<b) max = b; max else max = a; max // Note: No semicolon here Note: // Note: No semicolon here Note: The syntax is if (condition) statement-1 statement-1 else statement-2 statement-2 // if the condition is true, do statement-1 if // if not, do statement-2 if Stroustrup/Programming 12 12 Iteration (while loop) Iteration The world’s first “real program” running on a stored-program The computer (David Wheeler, Cambridge, May 6, 1949) computer // calculate and print a table of squares 0-99: // calculate int main() { int i = 0; while (i<100) { cout << i << '\t' << square(i) << '\n'; cout ++i ; // increment i // increment } } // (No, it wasn’t actually written in C++ .) // Stroustrup/Programming 13 13 Iteration (while loop) What it takes A loop variable (control variable); loop Initialize the control variable; Initialize A termination criterion; Increment the control variable; Something to do for each iteration; Something here: i here: int i = 0 int here: if i<100 is false, terminate is here: ++i here: ++i here: cout << … cout int i = 0; while (i<100) while { cout << i << '\t' << square(i) << '\n'; cout ++i ; // increment i // increment } Stroustrup/Programming 14 14 Iteration (for loop) Another iteration form: the for loop Another for You can collect all the control information in one You place, at the top, where it’s easy to see place, for (int i = 0; i<100; ++i) for { cout << i << '\t' << square(i) << '\n'; cout } That is, for (initialize; condition ; increment ) condition controlled statement Note: what is square(i)? Note: Stroustrup/Programming 15 15 Functions But what was square(i)? But square(i)? A call of the function square() square() call int square(int x) { return x*x; return } We define a function when we want to separate a We computation because it computation is logically separate makes the program text clearer (by naming the computation) is useful in more than one place in our program eases testing, distribution of labor, and maintenance Stroustrup/Programming 16 16 Control Flow int main() int square(int x) { { i=0; while (i<100) return x * x; { } square(i) i<100 } } i==100 Stroustrup/Programming 17 17 Functions Our function int square(int x) { return x*x; } is an example of Return_type function_name ( Parameter list ) Return_type // (type name, etc.) (type { // use each parameter in code // use return some_value; // of Return_type return some_value // of } Stroustrup/Programming 18 18 Another Example Earlier we looked at code to find the larger of two values. Earlier Here is a function that compares the two values and returns the larger value. int max(int a, int b) // this function takes 2 parameters this { if (a<b) return b; return else return a; return } int x = max(7, 9); int y = max(19, -27); int z = max(20, 20); // x becomes 9 // becomes // y becomes 19 // becomes // z becomes 20 becomes Stroustrup/Programming 19 19 Data for Iteration - Vector To do just about anything of interest, we need a collection of To data to work on. We can store this data in a vector. For example: vector // read some temperatures into a vector: read int main() { vector<double> temps; // declare a vector of type double to store vector<double> // temperatures – like 62.4 // temperatures double temp; // a variable for a single temperature value // variable while (cin>>temp) // cin reads a value and stores it in temp while cin temps.push_back(temp); // store the value of temp in the vector store // … do something … // do } // cin>>temp will return true until we reach the end of file or encounter // // something that isn’t a double: like the word “end” // something Stroustrup/Programming 20 20 Vector Vector is the most useful standard library data type a vector<T> holds an sequence of values of type T vector<T> Think of a vector this way A vector named v contains 5 elements: {1, 4, 2, 3, 5}: vector size() v: 5 v[0] v’s elements: v[1] v[2] 1 4 2 Stroustrup/Programming v[3] v[4] 3 5 21 21 vector<int> v; v: Vectors // start off empty // start 0 v.push_back(1); // add an element with the value 1 // v: 1 1 v.push_back(4); // add an element with the value 4 at end (“the back”) // add at v: 2 1 4 v.push_back(3); // add an element with the value 3 at end (“the back”) // add at v[0] v[0] v: 3 v[1] 1 Stroustrup/Programming v[2] 4 3 22 22 Vectors Once you get your data into a vector you can easily manipulate it: // compute mean (average) and median temperatures: // compute int main() { vector<double> temps; // temperatures in Fahrenheit, e.g. 64.6 temperatures double temp; while (cin>>temp) temps.push_back(temp); // read and put into vector while read double sum = 0; for (int i = 0; i< temps.size(); ++i) sum += temps[i]; for // sums temperatures sums cout << "Mean temperature: " << sum/temps.size() << endl; sort(temps.begin(),temps.end()); cout << "Median temperature: " << temps[temps.size()/2] << endl; } Stroustrup/Programming 23 23 Combining Language Features You can write many new programs by combining You language features, built-in types, and user-defined types in new and interesting ways. types So far, we have Variables and literals of types bool, char, int, double bool, Variables vector, push_back(), [ ] (subscripting) !=, ==, =, +, -, +=, <, &&, ||, ! max( ), sort( ), cin>>, cout<< if, for, while You can write a lot of different programs with these You language features! Let’s try to use them in a slightly different way… different Stroustrup/Programming 24 24 Example – Word List // “boilerplate” left out // “boilerplate” vector<string> words; string s; while (cin>>s && s != "quit") while words.push_back(s); sort(words.begin(), words.end()); // && means AND && // sort the words we read // sort for (int i=0; i<words.size(); ++i) for cout<<words[i]<< "\n"; cout<<words[i]<< /* /* read a bunch of strings into a vector of strings, sort read them into lexicographical order (alphabetical order), and print the strings from the vector to see what we have. */ */ Stroustrup/Programming 25 25 Word list – Eliminate Duplicates // Note that duplicate words were printed multiple times. For // Note // example “the the the”. That’s tedious, let’s eliminate duplicates: // example vector<string> words; vector<string> string s; while (cin>>s && s!= "quit") words.push_back(s); sort(words.begin(), words.end()); for (int i=1; i<words.size(); ++i) for if(words[i-1]==words[i]) “get rid of words[i]” // (pseudocode) for (int i=0; i<words.size(); ++i) cout<<words[i]<< "\n"; // there are many ways to “get rid of words[i]”; many of them are messy // there // (that’s typical). Our job as programmers is to choose a simple clean (that’s // solution – given constraints – time, run-time, memory. // solution Stroustrup/Programming Stroustrup/Programming 26 26 Example (cont.) Eliminate Words! // Eliminate the duplicate words by copying only unique words: // Eliminate vector<string> words; vector<string> string s; while (cin>>s && s!= "quit") words.push_back(s); sort(words.begin(), words.end()); vector<string>w2; if (0<words.size()) { // Note style { } // Note w2.push_back(words[0]); for (int i=1; i<words.size(); ++i) for if(words[i-1]!=words[i]) if(words[i-1]!=words[i]) w2.push_back(words[i]); } cout<< "found " << words.size()-w2.size() << " duplicates\n"; for (int i=0; i<w2.size(); ++i) cout << w2[i] << "\n"; Stroustrup/Programming 27 27 Algorithm We just used a simple algorithm An algorithm is (from Google search) “a logical arithmetical or computational procedure that, if correctly logical applied, ensures the solution of a problem.” – Harper Collins Harper “a set of rules for solving a problem in a finite number of steps, as for set finding the greatest common divisor.” – Random House Random “a detailed sequence of actions to perform or accomplish some task. detailed Named after an Iranian mathematician, Al-Khawarizmi. Technically, an algorithm must reach a result after a finite number of steps, …The term is also used loosely for any sequence of actions (which may or may not terminate).” – Webster’s We eliminated the duplicates by first sorting the vector We (so that duplicates are adjacent), and then copying only strings that differ from their predecessor into another vector. vector. Stroustrup/Programming 28 28 Ideal Basic language features and libraries should be Basic usable in essentially arbitrary combinations. usable We are not too far from that ideal. If a combination of features and types make sense, If it will probably work. it The compiler helps by rejecting some absurdities. Stroustrup/Programming 29 29 The next lecture How to deal with errors Stroustrup/Programming 30 30 ...
View Full Document

This note was uploaded on 02/18/2012 for the course CSCE 121 taught by Professor Walter daugherity during the Fall '09 term at Texas A&M.

Ask a homework question - tutors are online