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

Similar documents
Chapter 4 Computation

Chapter 4. Computation. Bjarne Stroustrup.

CS 11 C track: lecture 1

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

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

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

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

Python Programming: An Introduction to Computer Science

How do we evaluate algorithms?

CMPT 125 Assignment 2 Solutions

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

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

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

A graphical view of big-o notation. c*g(n) f(n) f(n) = O(g(n))

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

Examples and Applications of Binary Search

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

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

Working with Batches of Data

Overview. Common tasks. Observation. Chapter 20 The STL (containers, iterators, and algorithms) 8/13/18. Bjarne Stroustrup

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

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

Lecture 5. Counting Sort / Radix Sort

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

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

Algorithm. Counting Sort Analysis of Algorithms

Behavioral Modeling in Verilog

Chapter 4 The Datapath

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

Analysis of Algorithms

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

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

Homework 1 Solutions MA 522 Fall 2017

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

Python Programming: An Introduction to Computer Science

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

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

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

Analysis of Algorithms

BOOLEAN MATHEMATICS: GENERAL THEORY

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1

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

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

Data Structures and Algorithms. Analysis of Algorithms

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

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

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

Computational Geometry

Computers and Scientific Thinking

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

NTH, GEOMETRIC, AND TELESCOPING TEST

1.2 Binomial Coefficients and Subsets

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

CIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8)

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

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

Appendix D. Controller Implementation

CSE 2320 Notes 8: Sorting. (Last updated 10/3/18 7:16 PM) Idea: Take an unsorted (sub)array and partition into two subarrays such that.

Sorting in Linear Time. Data Structures and Algorithms Andrei Bulatov

Java Expressions & Flow Control

Lecture 1: Introduction and Strassen s Algorithm

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

Data Structures Week #5. Trees (Ağaçlar)

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

Lecture 9: Exam I Review

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

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

CSE 111 Bio: Program Design I Class 11: loops

Computer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.

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

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

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

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

Algorithm Design Techniques. Divide and conquer Problem

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

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

CIS 121. Introduction to Trees

Exercise 6 (Week 42) For the foreign students only.

Ones Assignment Method for Solving Traveling Salesman Problem

ECE4050 Data Structures and Algorithms. Lecture 6: Searching

Elementary Educational Computer

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

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

Lecture 6. Lecturer: Ronitt Rubinfeld Scribes: Chen Ziv, Eliav Buchnik, Ophir Arie, Jonathan Gradstein

Arithmetic Sequences

COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 4. The Processor. Part A Datapath Design

condition w i B i S maximum u i

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

BaanERP Tools. Programming features

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

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

COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

Civil Engineering Computation

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

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

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

MR-2010I %MktBSize Macro 989. %MktBSize Macro

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

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

Transcription:

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