Chapter 4 Computatio Bjare Stroustrup www.stroustrup.com/programmig Abstract Today, I ll preset the basics of computatio. I particular, we ll discuss expressios, how to iterate over a series of values ( iteratio ), ad select betwee two alterative actios ( selectio ). I ll also show how a particular sub-computatio ca be amed ad specified separately as a fuctio. To be able to perform more realistic computatios, I will itroduce the vector type to hold sequeces of values. Selectio, Iteratio, Fuctio, Vector Stroustrup/Programmig/2015 2 Computatio Overview What is computable? How best to compute it? Abstractios, algorithms, heuristics, data structures Laguage costructs ad ideas Sequetial order of executio Expressios ad Statemets Selectio Iteratio Fuctios Vectors You already kow most of this Note: You kow how to do arithmetic d = a+b*c You kow how to select if this is true, do that; otherwise do somethig else You kow how to iterate do this util you are fiished do that 100 times lather, rise, repeat You kow how to do fuctios go ask Joe ad brig back the aswer hey Joe, calculate this for me ad sed me the aswer What I will show you today is mostly just vocabulary ad sytax for what you already kow Stroustrup/Programmig/2015 3 Stroustrup/Programmig/2015 4 1
(iput) data Computatio Code, ofte messy, ofte a lot of code data (output) data Iput: from keyboard, files, other iput devices, other programs, other parts of a program Computatio what our program will do with the iput to produce the output. Output: to scree, files, other output devices, other programs, other parts of a program Computatio Our job is to express computatios Correctly Simply Efficietly Oe tool is called Divide ad Coquer to break up big computatios ito may little oes Aother tool is Abstractio Provide a higher-level cocept that hides detail Orgaizatio of data is ofte the key to good code Iput/output formats Protocols Data structures Note the emphasis o structure ad orgaizatio You do t get good code just by writig a lot of statemets Stroustrup/Programmig/2015 5 Stroustrup/Programmig/2015 6 Laguage features Each programmig laguage feature exists to express a fudametal idea For example + : additio * : multiplicatio if (expressio) statemet else statemet ; selectio while (expressio) statemet ; iteratio f(x); fuctio/operatio We combie laguage features to create programs Expressios // compute area: it legth = 20; // the simplest expressio: a literal (here, 20) // (here used to iitialize a variable) it width = 40; it area = legth*width; // a multiplicatio it average = (legth+width)/2; // additio ad divisio The usual rules of precedece apply: a*b+c/d meas (a*b)+(c/d) ad ot a*(b+c)/d. If i doubt, parethesize. If complicated, parethesize. Do t write absurdly complicated expressios: a*b+c/d*(e-f/g)/h+7 // too complicated Choose meaigful ames. Stroustrup/Programmig/2015 7 Stroustrup/Programmig/2015 8 2
Expressios Expressios are made out of operators ad operads Operators specify what is to be doe Operads specify the data for the operators to work with Boolea type: bool (true ad false) Equality operators: = = (equal),!= (ot equal) Logical operators: && (ad), (or),! (ot) Relatioal operators: < (less tha), > (greater tha), <=, >= Character type: char (e.g., 'a', '7', ad '@') Iteger types: short, it, log arithmetic operators: +, -, *, /, % (remaider) Floatig-poit types: e.g., float, double (e.g., 12.45 ad 1.234e3) arithmetic operators: +, -, *, / Cocise Operators For may biary operators, there are (roughly) equivalet more cocise operators For example a += c meas a = a+c a *= scale meas a = a*scale ++a meas a += 1 or a = a+1 Cocise operators are geerally better to use (clearer, express a idea more directly) Stroustrup/Programmig/2015 9 Stroustrup/Programmig/2015 10 Statemets A statemet is a expressio followed by a semicolo, or a declaratio, or a cotrol statemet that determies the flow of cotrol For example a = b; double d2 = 2.5; if (x == 2) y = 4; while (ci >> umber) umbers.push_back(umber); it average = (legth+width)/2; retur x; You may ot uderstad all of these just ow, but you will Selectio Sometimes we must select betwee alteratives For example, suppose we wat to idetify the larger of two values. We ca do this with a if statemet if (a<b) // Note: No semicolo here max = b; else // Note: No semicolo here max = a; The sytax is if (coditio) statemet-1 else statemet-2 // if the coditio is true, do statemet-1 // if ot, do statemet-2 Stroustrup/Programmig/2015 11 Stroustrup/Programmig/2015 12 3
Iteratio (while loop) The world s first real program ruig o a stored-program computer (David Wheeler, Cambridge, May 6, 1949) // calculate ad prit a table of squares 0-99: it mai() it i = 0; while (i<100) cout << i << '\t' << square(i) << '\'; ++i ; // icremet i // (No, it was t actually writte i C++ J.) What it takes Iteratio (while loop) A loop variable (cotrol variable); here: i Iitialize the cotrol variable; here: it i = 0 A termiatio criterio; here: if i<100 is false, termiate Icremet the cotrol variable; here: ++i Somethig to do for each iteratio; here: cout << it i = 0; while (i<100) cout << i << '\t' << square(i) << '\'; ++i ; // icremet i Stroustrup/Programmig/2015 13 Stroustrup/Programmig/2015 14 Iteratio (for loop) Aother iteratio form: the for loop You ca collect all the cotrol iformatio i oe place, at the top, where it s easy to see for (it i = 0; i<100; ++i) cout << i << '\t' << square(i) << '\'; That is, for (iitialize; coditio ; icremet ) cotrolled statemet Note: what is square(i)? Fuctios But what was square(i)? A call of the fuctio square() it square(it x) retur x*x; We defie a fuctio whe we wat to separate a computatio because it is logically separate makes the program text clearer (by amig the computatio) is useful i more tha oe place i our program eases testig, distributio of labor, ad maiteace Stroustrup/Programmig/2015 15 Stroustrup/Programmig/2015 16 4
i<100 it mai() i=0; while (i<100) square(i); i==100 Cotrol Flow it square(it x) // compute square retur x * x; Our fuctio it square(it x) retur x*x; is a example of Fuctios Retur_type fuctio_ame ( Parameter list ) // (type ame, etc.) // use each parameter i code retur some_value; // of Retur_type Stroustrup/Programmig/2015 17 Stroustrup/Programmig/2015 18 Aother Example Earlier we looked at code to fid the larger of two values. Here is a fuctio that compares the two values ad returs the larger value. it max(it a, it b) // this fuctio takes 2 parameters if (a<b) retur b; else retur a; it x = max(7, 9); // x becomes 9 it y = max(19, -27); // y becomes 19 it z = max(20, 20); // z becomes 20 Data for Iteratio - Vector To do just about aythig of iterest, we eed a collectio of data to work o. We ca store this data i a vector. For example: // read some temperatures ito a vector: it mai() vector<double> temps; // declare a vector of type double to store // temperatures like 62.4 double temp; // a variable for a sigle temperature value while (ci>>temp) // ci reads a value ad stores it i temp temps.push_back(temp); // store the value of temp i the vector // do somethig // ci>>temp will retur true util we reach the ed of file or ecouter // somethig that is t a double: like the word ed Stroustrup/Programmig/2015 19 Stroustrup/Programmig/2015 20 5
Vector vector<it> v; // start off empty Vectors Vector is the most useful stadard library data type a vector<t> holds a sequece of values of type T Thik of a vector this way A vector amed v cotais 5 elemets: 1, 4, 2, 3, 5: v: 0 v.push_back(1); // add a elemet with the value 1 v: 1 1 size() v.push_back(4); // add a elemet with the value 4 at ed ( the back ) v: 5 v s elemets: v[0] v[1] v[2] v[3] v[4] 1 4 2 3 5 v: 2 1 4 v.push_back(3); // add a elemet with the value 3 at ed ( the back ) v: 3 v[0] v[1] v[2] 1 4 3 Stroustrup/Programmig/2015 21 Stroustrup/Programmig/2015 22 Vectors Oce you get your data ito a vector you ca easily maipulate it // compute mea (average) ad media temperatures: it mai() vector<double> temps; // temperatures i Fahreheit, e.g. 64.6 double temp; while (ci>>temp) temps.push_back(temp); // read ad put ito vector Traversig a vector Oce you get your data ito a vector you ca easily maipulate it Iitialize with a list vector<it> v = 1, 2, 3, 5, 8, 13 ; // iitialize with a list ofte we wat to look at each elemet of a vector i tur: double sum = 0; for (it i = 0; i< temps.size(); ++i) sum += temps[i]; // sums temperatures cout << "Mea temperature: " << sum/temps.size() << '\'; sort(temps); // from std_lib_facilities.h // or sort(temps.begi(), temps.ed(); cout << "Media temperature: " << temps[temps.size()/2] << '\'; for (it i = 0; i< v.size(); ++i) cout << v[i] << '\'; // list all elemets // there is a simpler kid of loop for that (a rage-for loop): for (it x : v) cout << x << '\'; // list all elemets // for each x i v Stroustrup/Programmig/2015 23 Stroustrup/Programmig/2015 24 6
Combiig Laguage Features You ca write may ew programs by combiig laguage features, built-i types, ad user-defied types i ew ad iterestig ways. So far, we have Variables ad literals of types bool, char, it, double vector, push_back(), [ ] (subscriptig)!=, ==, =, +, -, +=, <, &&,,! max( ), sort( ), ci>>, cout<< if, for, while You ca write a lot of differet programs with these laguage features! Let s try to use them i a slightly differet way // boilerplate left out Example Word List vector<strig> words; for (strig s; ci>>s && s!= "quit ; ) words.push_back(s); sort(words); for (strig s : words) cout << s << '\'; // sort the words we read // && meas AND /* read a buch of strigs ito a vector of strigs, sort them ito lexicographical order (alphabetical order), ad prit the strigs from the vector to see what we have. */ Stroustrup/Programmig/2015 25 Stroustrup/Programmig/2015 26 Word list Elimiate Duplicates // Note that duplicate words were prited multiple times. For // example the the the. That s tedious, let s elimiate duplicates: vector<strig> words; for (strig s; ci>>s && s!= "quit"; ) words.push_back(s); sort(words); for (it i=1; i<words.size(); ++i) if(words[i-1]==words[i]) get rid of words[i] // (pseudocode) for (strig s : words) cout << s << '\'; // there are may ways to get rid of words[i] ; may of them are messy // (that s typical). Our job as programmers is to choose a simple clea // solutio give costraits time, ru-time, memory. Example (cot.) Elimiate Words! // Elimiate the duplicate words by copyig oly uique words: vector<strig> words; for (strig s; ci>>s && s!= "quit"; ) words.push_back(s); sort(words); vector<strig>w2; if (0<words.size()) // ote style w2.push_back(words[0]); for (it i=1; i<words.size(); ++i) // ote: ot a rage-for if(words[i-1]!=words[i]) w2.push_back(words[i]); cout<< "foud " << words.size()-w2.size() << " duplicates\"; for (strig s : w2) cout << s << "\"; Stroustrup/Programmig/2015 27 Stroustrup/Programmig/2015 28 7
2 9 Algorithm We just used a simple algorithm A algorithm is (from Google search) a logical arithmetical or computatioal procedure that, if correctly applied, esures the solutio of a problem. Harper Collis a set of rules for solvig a problem i a fiite umber of steps, as for fidig the greatest commo divisor. Radom House a detailed sequece of actios to perform or accomplish some task. Named after a Iraia mathematicia, Al-Khawarizmi. Techically, a algorithm must reach a result after a fiite umber of steps, The term is also used loosely for ay sequece of actios (which may or may ot termiate). Webster s A algorithm has fiiteess, defiiteess, processes a fiite amout of iput, produces a fiite amout of output related to the iputs, ad has effectiveess. Kuth 3 0 Algorithm We elimiated the duplicates by first sortig the vector (so that duplicates are adjacet), ad the copyig oly strigs that differ from their predecessor ito aother vector. Stroustrup/Programmig /2015 Stroustrup/Programmig /2015 Ideal Basic laguage features ad libraries should be usable i essetially arbitrary combiatios. We are ot too far from that ideal. If a combiatio of features ad types make sese, it will probably work. The compiler helps by rejectig some absurdities. The ext lecture How to deal with errors Stroustrup/Programmig/2015 31 Stroustrup/Programmig/2015 32 8