SlideShare a Scribd company logo
Chapter 4Chapter 4
ComputationComputation
Bjarne StroustrupBjarne Stroustrup
www.stroustrup.com/Programmingwww.stroustrup.com/Programming
22
AbstractAbstract
 Today, I’ll present the basics of computation. InToday, I’ll present the basics of computation. In
particular, we’ll discuss expressions, how toparticular, we’ll discuss expressions, how to
iterate over a series of values (“iteration”), anditerate over a series of values (“iteration”), and
select between two alternative actionsselect between two alternative actions
(“selection”). I’ll also show how a particular sub-(“selection”). I’ll also show how a particular sub-
computation can be named and specifiedcomputation can be named and specified
separately as a function. To be able to performseparately as a function. To be able to perform
more realistic computations, I will introduce themore realistic computations, I will introduce the
vectorvector type to hold sequences of values.type to hold sequences of values.
 Selection, Iteration, Function, VectorSelection, Iteration, Function, Vector
Stroustrup/Programming/2015Stroustrup/Programming/2015
33
OverviewOverview
 ComputationComputation
 What is computable? How best to compute it?What is computable? How best to compute it?
 Abstractions, algorithms, heuristics, data structuresAbstractions, algorithms, heuristics, data structures
 Language constructs and ideasLanguage constructs and ideas
 Sequential order of executionSequential order of execution
 Expressions and StatementsExpressions and Statements
 SelectionSelection
 IterationIteration
 FunctionsFunctions
 VectorsVectors
Stroustrup/Programming/2015Stroustrup/Programming/2015
44
You already know most of thisYou already know most of this
 Note:Note:
 You know how to do arithmeticYou know how to do arithmetic
 d = a+b*cd = a+b*c
 You know how to selectYou know how to select
““if this is true, do that; otherwise do something else ”if this is true, do that; otherwise do something else ”
 You know how to “iterate”You know how to “iterate”
 ““do this until you are finished”do this until you are finished”
 ““do that 100 times”do that 100 times”
 You know how to do functionsYou know how to do functions
 ““go ask Joe and bring back the answer”go ask Joe and bring back the answer”
 ““hey Joe, calculate this for me and send me the answer”hey Joe, calculate this for me and send me the answer”
 What I will show you today is mostly just vocabulary andWhat I will show you today is mostly just vocabulary and
syntax for what you already knowsyntax for what you already know
Stroustrup/Programming/2015Stroustrup/Programming/2015
55
ComputationComputation
 Input: from keyboard, files, other input devices, other programs, otherInput: from keyboard, files, other input devices, other programs, other
parts of a programparts of a program
 Computation – what our program will do with the input to produce theComputation – what our program will do with the input to produce the
output.output.
 Output: to screen, files, other output devices, other programs, other partsOutput: to screen, files, other output devices, other programs, other parts
of a programof a program
(input) data (output) data
data
Code, often messy,
often a lot of code
Stroustrup/Programming/2015Stroustrup/Programming/2015
66
ComputationComputation
 Our job is to express computationsOur job is to express computations
 CorrectlyCorrectly
 SimplySimply
 EfficientlyEfficiently
 One tool is called Divide and ConquerOne tool is called Divide and Conquer
 to break up big computations into many little onesto break up big computations into many little ones
 Another tool is AbstractionAnother tool is Abstraction
 Provide a higher-level concept that hides detailProvide a higher-level concept that hides detail
 Organization of data is often the key to good codeOrganization of data is often the key to good code
 Input/output formatsInput/output formats
 ProtocolsProtocols
 Data structuresData structures
 Note the emphasis on structure and organizationNote the emphasis on structure and organization
 You don’t get good code just by writing a lot of statementsYou don’t get good code just by writing a lot of statements
Stroustrup/Programming/2015Stroustrup/Programming/2015
77
Language featuresLanguage features
 Each programming language feature exists to expressEach programming language feature exists to express
a fundamental ideaa fundamental idea
 For exampleFor example
 ++ : addition: addition
 ** : multiplication: multiplication
 if (if (expressionexpression)) statementstatement elseelse statement ;statement ; selectionselection
 while (while (expressionexpression)) statementstatement ;; iterationiteration
 f(x);f(x); function/operationfunction/operation
 ……
 We combine language features to create programsWe combine language features to create programs
Stroustrup/Programming/2015Stroustrup/Programming/2015
88
ExpressionsExpressions
//// compute area:compute area:
int length = 20;int length = 20; //// the simplest expression: a literal (here, 20)the simplest expression: a literal (here, 20)
//// (here used to initialize a variable)(here used to initialize a variable)
int width = 40;int width = 40;
int area = length*width;int area = length*width; //// a multiplicationa multiplication
int average = (length+width)/2;int average = (length+width)/2; //// addition and divisionaddition and division
The usual rules of precedence apply:The usual rules of precedence apply:
a*b+c/da*b+c/d meansmeans (a*b)+(c/d)(a*b)+(c/d) and notand not a*(b+c)/da*(b+c)/d..
If in doubt, parenthesize. If complicated, parenthesize.If in doubt, parenthesize. If complicated, parenthesize.
Don’t write “absurdly complicated” expressions:Don’t write “absurdly complicated” expressions:
a*b+c/d*(e-f/g)/h+7a*b+c/d*(e-f/g)/h+7 //// too complicatedtoo complicated
Choose meaningful names.Choose meaningful names.
Stroustrup/Programming/2015Stroustrup/Programming/2015
99
ExpressionsExpressions
 Expressions are made out of operators and operandsExpressions are made out of operators and operands
 Operators specify what is to be doneOperators specify what is to be done
 Operands specify the data for the operators to work withOperands specify the data for the operators to work with
 Boolean type:Boolean type: boolbool ((truetrue andand falsefalse))
 Equality operators:Equality operators: = == = (equal),(equal), !=!= (not equal)(not equal)
 Logical operators:Logical operators: &&&& (and),(and), |||| (or),(or), !! (not)(not)
 Relational operators:Relational operators: << (less than),(less than), >> (greater than),(greater than), <=<=,, >=>=
 Character type:Character type: charchar (e.g.,(e.g., 'a''a',, '7''7', and, and '@''@'))
 Integer types:Integer types: short, int, longshort, int, long
 arithmetic operators:arithmetic operators: +, -, *, /, %+, -, *, /, % (remainder)(remainder)
 Floating-point types: e.g.,Floating-point types: e.g., float, doublefloat, double (e.g.,(e.g., 12.4512.45 andand 1.234e31.234e3))
 arithmetic operators:arithmetic operators: +, -, *, /+, -, *, /
Stroustrup/Programming/2015Stroustrup/Programming/2015
1010
Concise OperatorsConcise Operators
 For many binary operators, there are (roughly) equivalentFor many binary operators, there are (roughly) equivalent
more concise operatorsmore concise operators
 For exampleFor example
 a += ca += c meansmeans a = a+ca = a+c
 a *= scalea *= scale meansmeans a = a*scalea = a*scale
 ++a++a meansmeans a += 1a += 1
oror a = a+1a = a+1
 ““Concise operators” are generally better to useConcise operators” are generally better to use
(clearer, express an idea more directly)(clearer, express an idea more directly)
Stroustrup/Programming/2015Stroustrup/Programming/2015
1111
StatementsStatements
 A statement isA statement is
 an expression followed by a semicolon, oran expression followed by a semicolon, or
 a declaration, ora declaration, or
 a “control statement” that determines the flow of controla “control statement” that determines the flow of control
 For exampleFor example
 a = b;a = b;
 double d2 = 2.5;double d2 = 2.5;
 if (x == 2) y = 4;if (x == 2) y = 4;
 while (cin >> number) numbers.push_back(number);while (cin >> number) numbers.push_back(number);
 int average = (length+width)/2;int average = (length+width)/2;
 return x;return x;
 You may not understand all of these just now, but you will …You may not understand all of these just now, but you will …
Stroustrup/Programming/2015Stroustrup/Programming/2015
1212
SelectionSelection
 Sometimes we must select between alternativesSometimes we must select between alternatives
 For example, suppose we want to identify the larger of twoFor example, suppose we want to identify the larger of two
values. We can do this with anvalues. We can do this with an ifif statementstatement
if (a<b)if (a<b) //// Note: No semicolon hereNote: No semicolon here
max = b;max = b;
elseelse //// Note: No semicolon hereNote: No semicolon here
max = a;max = a;
 The syntax isThe syntax is
if (condition)if (condition)
statement-1statement-1 //// if the condition is true, do statement-1if the condition is true, do statement-1
elseelse
statement-2statement-2 //// if not, do statement-2if not, do statement-2
Stroustrup/Programming/2015Stroustrup/Programming/2015
1313
Iteration (while loop)Iteration (while loop)
 The world’s first “real program” running on a stored-programThe world’s first “real program” running on a stored-program
computer (David Wheeler, Cambridge, May 6, 1949)computer (David Wheeler, Cambridge, May 6, 1949)
//// calculate and print a table of squares 0-99:calculate and print a table of squares 0-99:
int main()int main()
{{
int i = 0;int i = 0;
while (i<100) {while (i<100) {
cout << i <<cout << i << ''tt'' << square(i) <<<< square(i) << ''nn'';;
++i ;++i ; //// incrementincrement ii
}}
}}
//// (No, it wasn’t actually written in C++(No, it wasn’t actually written in C++ .).)
Stroustrup/Programming/2015Stroustrup/Programming/2015
1414
Iteration (while loop)Iteration (while loop)
 What it takesWhat it takes
 A loop variable (control variable);A loop variable (control variable); here:here: ii
 Initialize the control variable;Initialize the control variable; here:here: int i = 0int i = 0
 AA termination criterion;termination criterion; here: ifhere: if i<100i<100 is false, terminateis false, terminate
 Increment the control variable;Increment the control variable; here:here: ++i++i
 Something to do for each iteration;Something to do for each iteration; here:here: cout << …cout << …
int i = 0;int i = 0;
while (i<100) {while (i<100) {
cout << i <<cout << i << ''tt'' << square(i) <<<< square(i) << ''nn'';;
++i ;++i ; //// incrementincrement ii
}}
Stroustrup/Programming/2015Stroustrup/Programming/2015
1515
Iteration (for loop)Iteration (for loop)
 Another iteration form: theAnother iteration form: the forfor looploop
 You can collect all the control information in oneYou can collect all the control information in one
place, at the top, where it’s easy to seeplace, at the top, where it’s easy to see
for (int i = 0; i<100; ++i) {for (int i = 0; i<100; ++i) {
cout << i <<cout << i << ''tt'' << square(i) <<<< square(i) << ''nn'';;
}}
That is,That is,
for (for (initializeinitialize;; conditioncondition ;; incrementincrement ))
controlled statementcontrolled statement
Note: what isNote: what is square(i)square(i)??
Stroustrup/Programming/2015Stroustrup/Programming/2015
1616
FunctionsFunctions
 But what wasBut what was square(i)?square(i)?
 A call of the functionA call of the function square()square()
int square(int x)int square(int x)
{{
return x*x;return x*x;
}}
 We define a function when we want to separate aWe define a function when we want to separate a
computation because itcomputation because it
 is logically separateis logically separate
 makes the program text clearer (by naming the computation)makes the program text clearer (by naming the computation)
 is useful in more than one place in our programis useful in more than one place in our program
 eases testing, distribution of labor, and maintenanceeases testing, distribution of labor, and maintenance
Stroustrup/Programming/2015Stroustrup/Programming/2015
1717
Control FlowControl Flow
int main()int main()
{{
i=0;i=0;
while (i<100)while (i<100)
{{
square(i);square(i);
}}
}}
int square(int x)int square(int x)
{{
//// compute square rootcompute square root
return x * x;return x * x;
}}i<100
i==100
Stroustrup/Programming/2015Stroustrup/Programming/2015
1818
FunctionsFunctions
 Our functionOur function
int square(int x)int square(int x)
{{
return x*x;return x*x;
}}
is an example ofis an example of
Return_type function_nameReturn_type function_name (( Parameter listParameter list ))
//// (type name, etc.)(type name, etc.)
{{
//// use each parameter in codeuse each parameter in code
returnreturn some_valuesome_value;; //// ofof Return_typeReturn_type
}}
Stroustrup/Programming/2015Stroustrup/Programming/2015
1919
Another ExampleAnother Example
 Earlier we looked at code to find the larger of two values.Earlier we looked at code to find the larger of two values.
Here is a function that compares the two values and returnsHere is a function that compares the two values and returns
the larger value.the larger value.
int max(int a, int b)int max(int a, int b) //// this function takes 2 parametersthis function takes 2 parameters
{{
if (a<b)if (a<b)
return b;return b;
elseelse
return a;return a;
}}
int x = max(7, 9);int x = max(7, 9); //// x becomes 9x becomes 9
int y = max(19, -27);int y = max(19, -27); //// y becomes 19y becomes 19
int z = max(20, 20);int z = max(20, 20); //// z becomes 20z becomes 20
Stroustrup/Programming/2015Stroustrup/Programming/2015
2020
Data for Iteration - VectorData for Iteration - Vector
 To do just about anything of interest, we need a collection ofTo do just about anything of interest, we need a collection of
data to work on. We can store this data in adata to work on. We can store this data in a vectorvector. For example:. For example:
//// read some temperatures into a vector:read some temperatures into a vector:
int main()int main()
{{
vector<double> temps;vector<double> temps; //// declare a vector of type double to storedeclare a vector of type double to store
//// temperatures – like 62.4temperatures – like 62.4
double temp;double temp; //// a variable for a single temperature valuea variable for a single temperature value
while (cin>>temp)while (cin>>temp) //// cin reads a value and stores it in tempcin reads a value and stores it in temp
temps.push_back(temp);temps.push_back(temp); //// store the value of temp in the vectorstore the value of temp in the vector
//// … do something …… do something …
}}
//// cin>>tempcin>>temp will return true until we reach the end of file or encounterwill return true until we reach the end of file or encounter
//// something that isn’t a double: like the word “end”something that isn’t a double: like the word “end”
Stroustrup/Programming/2015Stroustrup/Programming/2015
2121
VectorVector
 Vector is the most useful standard library data typeVector is the most useful standard library data type
 aa vector<T>vector<T> holds an sequence of values of typeholds an sequence of values of type TT
 Think of a vector this wayThink of a vector this way
A vector namedA vector named vv contains 5 elements: {1, 4, 2, 3, 5}:contains 5 elements: {1, 4, 2, 3, 5}:
1 4 2 3 5
5v:
v’s elements:
v[0] v[1] v[2] v[3] v[4]
size()
Stroustrup/Programming/2015Stroustrup/Programming/2015
2222
VectorsVectors
vector<int> v;vector<int> v; //// start off emptystart off empty
v.push_back(1);v.push_back(1); //// add an element with the valueadd an element with the value 11
v.push_back(4);v.push_back(4); //// add an element with the valueadd an element with the value 44 at end (“the back”)at end (“the back”)
v.push_back(3);v.push_back(3); //// add an element with the valueadd an element with the value 33 at end (“the back”)at end (“the back”)
v[0]v[0] v[1] v[2]v[1] v[2]
0v:
3
2
1 1
41
341
v:
v:
v:
Stroustrup/Programming/2015Stroustrup/Programming/2015
2323
VectorsVectors
 Once you get your data into a vector you can easily manipulate itOnce you get your data into a vector you can easily manipulate it
//// compute mean (average) and median temperatures:compute mean (average) and median temperatures:
int main()int main()
{{
vector<double> temps;vector<double> temps; //// temperatures in Fahrenheit, e.g. 64.6temperatures in Fahrenheit, e.g. 64.6
double temp;double temp;
while (cin>>temp) temps.push_back(temp); //while (cin>>temp) temps.push_back(temp); // read and put into vectorread and put into vector
double sum = 0;double sum = 0;
for (int i = 0; i< temps.size(); ++i) sum += temps[i]; //for (int i = 0; i< temps.size(); ++i) sum += temps[i]; // sums temperaturessums temperatures
cout << "Mean temperature: " << sum/temps.size() << 'n';cout << "Mean temperature: " << sum/temps.size() << 'n';
sort(temps);sort(temps); //// from std_lib_facilities.hfrom std_lib_facilities.h
//// or sort(temps.begin(), temps.end();or sort(temps.begin(), temps.end();
cout << "Median temperature: " << temps[temps.size()/2] << 'n';cout << "Median temperature: " << temps[temps.size()/2] << 'n';
}}
Stroustrup/Programming/2015Stroustrup/Programming/2015
2424
Traversing a vectorTraversing a vector
 Once you get your data into a vector you can easily manipulate itOnce you get your data into a vector you can easily manipulate it
 Initialize with a listInitialize with a list
 vector<int> v = { 1, 2, 3, 5, 8, 13 }; //vector<int> v = { 1, 2, 3, 5, 8, 13 }; // initialize with a listinitialize with a list
 often we want to look at each element of a vector in turn:often we want to look at each element of a vector in turn:
for (int i = 0; i< v.size(); ++i) cout << v[i] << 'n'; //for (int i = 0; i< v.size(); ++i) cout << v[i] << 'n'; // list all elementslist all elements
//// there is a simpler kind of loop for that (a range-for loop):there is a simpler kind of loop for that (a range-for loop):
for (int i : v) cout << x << 'n'; //for (int i : v) cout << x << 'n'; // list all elementslist all elements
//// for each x in v …for each x in v …
Stroustrup/Programming/2015Stroustrup/Programming/2015
2525
Combining Language FeaturesCombining Language Features
 You can write many new programs by combiningYou can write many new programs by combining
language features, built-in types, and user-definedlanguage features, built-in types, and user-defined
types in new and interesting ways.types in new and interesting ways.
 So far, we haveSo far, we have
 Variables and literals of typesVariables and literals of types bool, char, int, doublebool, char, int, double

vector, push_back(), [ ]vector, push_back(), [ ] (subscripting)(subscripting)
 !=, ==, =, +, -, +=, <, &&, ||, !!=, ==, =, +, -, +=, <, &&, ||, !
 max( ), sort( ), cin>>, cout<<max( ), sort( ), cin>>, cout<<
 if, for, whileif, for, while
 You can write a lot of different programs with theseYou can write a lot of different programs with these
language features! Let’s try to use them in a slightlylanguage features! Let’s try to use them in a slightly
different way…different way…
Stroustrup/Programming/2015Stroustrup/Programming/2015
2626
Example – Word ListExample – Word List
//// “boilerplate” left out“boilerplate” left out
vector<string> words;vector<string> words;
for (string s; cin>>s && s != "quit“; )for (string s; cin>>s && s != "quit“; ) //// && means AND&& means AND
words.push_back(s);words.push_back(s);
sort(words);sort(words); //// sort the words we readsort the words we read
for (string s : words)for (string s : words)
cout << s << 'n';cout << s << 'n';
/*/*
read a bunch of strings into a vector of strings, sortread a bunch of strings into a vector of strings, sort
them into lexicographical order (alphabetical order),them into lexicographical order (alphabetical order),
and print the strings from the vector to see what we have.and print the strings from the vector to see what we have.
*/*/
Stroustrup/Programming/2015Stroustrup/Programming/2015
2727
Word list – Eliminate DuplicatesWord list – Eliminate Duplicates
//// Note that duplicate words were printed multiple times. ForNote that duplicate words were printed multiple times. For
//// example “the the the”. That’s tedious, let’s eliminate duplicates:example “the the the”. That’s tedious, let’s eliminate duplicates:
vector<string> words;vector<string> words;
for (string s; cin>>s && s!= "quit"; )for (string s; cin>>s && s!= "quit"; )
words.push_back(s);words.push_back(s);
sort(words);sort(words);
for (int i=1; i<words.size(); ++i)for (int i=1; i<words.size(); ++i)
if(words[i-1]==words[i])if(words[i-1]==words[i])
““get rid of words[i]” // (pseudocode)get rid of words[i]” // (pseudocode)
for (string s : words)for (string s : words)
cout << s << 'n';cout << s << 'n';
//// there are many ways to “get rid of words[i]”; many of them are messythere are many ways to “get rid of words[i]”; many of them are messy
//// (that’s typical). Our job as programmers is to choose a simple clean(that’s typical). Our job as programmers is to choose a simple clean
//// solution – given constraints – time, run-time, memory.solution – given constraints – time, run-time, memory.
Stroustrup/Programming/2015Stroustrup/Programming/2015
2828
Example (cont.) Eliminate Words!Example (cont.) Eliminate Words!
//// Eliminate the duplicate words by copying only unique words:Eliminate the duplicate words by copying only unique words:
vector<string> words;vector<string> words;
for (string s; cin>>s && s!= "quit"; )for (string s; cin>>s && s!= "quit"; )
words.push_back(s);words.push_back(s);
sort(words);sort(words);
vector<string>w2;vector<string>w2;
if (0<words.size()) {if (0<words.size()) { //// note style { }note style { }
w2.push_back(words[0]);w2.push_back(words[0]);
for (int i=1; i<words.size(); ++i) //for (int i=1; i<words.size(); ++i) // note: not a range-note: not a range-forfor
if(words[i-1]!=words[i])if(words[i-1]!=words[i])
w2.push_back(words[i]);w2.push_back(words[i]);
}}
cout<< "found " << words.size()-w2.size() << " duplicatesn";cout<< "found " << words.size()-w2.size() << " duplicatesn";
for (string s : w2)for (string s : w2)
cout << s << "n";cout << s << "n";
Stroustrup/Programming/2015Stroustrup/Programming/2015
2929
AlgorithmAlgorithm
 We just used a simple algorithmWe just used a simple algorithm
 An algorithm is (from Google search)An algorithm is (from Google search)
 ““a logical arithmetical or computational procedure that, if correctlya logical arithmetical or computational procedure that, if correctly
applied, ensures the solution of a problem.” –applied, ensures the solution of a problem.” – Harper CollinsHarper Collins
 ““a set of rules for solving a problem in a finite number of steps, as fora set of rules for solving a problem in a finite number of steps, as for
finding the greatest common divisor.” –finding the greatest common divisor.” – Random HouseRandom House
 ““a detailed sequence of actions to perform or accomplish some task.a detailed sequence of actions to perform or accomplish some task.
Named after an Iranian mathematician, Al-Khawarizmi. Technically, anNamed after an Iranian mathematician, Al-Khawarizmi. Technically, an
algorithm must reach a result after a finite number of steps, …The term isalgorithm 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 notalso used loosely for any sequence of actions (which may or may not
terminate).” –terminate).” – Webster’sWebster’s
 We eliminated the duplicates by first sorting the vectorWe eliminated the duplicates by first sorting the vector
(so that duplicates are adjacent), and then copying only(so that duplicates are adjacent), and then copying only
strings that differ from their predecessor into anotherstrings that differ from their predecessor into another
vector.vector.
Stroustrup/Programming/2015Stroustrup/Programming/2015
3030
IdealIdeal
 Basic language features and libraries should beBasic language features and libraries should be
usable in essentially arbitrary combinations.usable in essentially arbitrary combinations.
 We are not too far from that ideal.We are not too far from that ideal.
 If a combination of features and types make sense,If a combination of features and types make sense,
it will probably work.it will probably work.
 The compiler helps by rejecting some absurdities.The compiler helps by rejecting some absurdities.
Stroustrup/Programming/2015Stroustrup/Programming/2015
3131
The next lectureThe next lecture
 How to deal with errorsHow to deal with errors
Stroustrup/Programming/2015Stroustrup/Programming/2015

More Related Content

PDF
C Programming Assignment
DOC
Assignment c programming
PPT
Object Orientation vs. Functional Programming in Python
PDF
CS4200 2019 | Lecture 2 | syntax-definition
PDF
CS4200 2019 | Lecture 4 | Syntactic Services
PDF
Declare Your Language: Type Checking
PPTX
Functional programming
PDF
Declare Your Language: Name Resolution
C Programming Assignment
Assignment c programming
Object Orientation vs. Functional Programming in Python
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 4 | Syntactic Services
Declare Your Language: Type Checking
Functional programming
Declare Your Language: Name Resolution

What's hot (20)

PDF
Declare Your Language: Transformation by Strategic Term Rewriting
PDF
Functional programming ii
PDF
Compiler Construction | Lecture 9 | Constraint Resolution
PDF
Compiler Construction | Lecture 8 | Type Constraints
PPTX
An Introduction : Python
PDF
Tutorial on c language programming
PDF
CS4200 2019 | Lecture 3 | Parsing
PDF
Functions, Strings ,Storage classes in C
PPT
Hooking signals and dumping the callstack
PPTX
C language
PDF
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
PPTX
Module 3-Functions
PDF
Compiler Construction | Lecture 4 | Parsing
PPTX
Module 5-Structure and Union
PPTX
Module 1:Introduction
PPTX
Fundamentals of c programming
PDF
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
PPT
Antlr V3
PPS
C programming session 05
Declare Your Language: Transformation by Strategic Term Rewriting
Functional programming ii
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 8 | Type Constraints
An Introduction : Python
Tutorial on c language programming
CS4200 2019 | Lecture 3 | Parsing
Functions, Strings ,Storage classes in C
Hooking signals and dumping the callstack
C language
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
Module 3-Functions
Compiler Construction | Lecture 4 | Parsing
Module 5-Structure and Union
Module 1:Introduction
Fundamentals of c programming
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Antlr V3
C programming session 05
Ad

Similar to Computation Chapter 4 (20)

PPT
Lập trình C
PPTX
lecture 2.pptx
PPT
C tutorial
PPT
C tutorial
PPT
C tutorial
PPTX
Php basics
PPTX
C++ lecture 01
PPS
Foundations of Programming Part I
PPT
Python Programming Introduction demo.ppt
PPTX
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
PPT
C tutorial
PPT
C Tutorials
PPTX
the refernce of programming C notes ppt.pptx
PPT
C463_02_python.ppt,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
PPT
C463_02intoduction_to_python_to learnGAI.ppt
PPTX
Introduction to learn and Python Interpreter
PDF
Python for scientific computing
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
PPT
introduction to python in english presentation file
DOCX
Program 1 – CS 344This assignment asks you to write a bash.docx
Lập trình C
lecture 2.pptx
C tutorial
C tutorial
C tutorial
Php basics
C++ lecture 01
Foundations of Programming Part I
Python Programming Introduction demo.ppt
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
C tutorial
C Tutorials
the refernce of programming C notes ppt.pptx
C463_02_python.ppt,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
C463_02intoduction_to_python_to learnGAI.ppt
Introduction to learn and Python Interpreter
Python for scientific computing
03 and 04 .Operators, Expressions, working with the console and conditional s...
introduction to python in english presentation file
Program 1 – CS 344This assignment asks you to write a bash.docx
Ad

More from Inocentshuja Ahmad (20)

PDF
Bottom up parser
PPTX
7th lec overview - latest
PPTX
6th lec infrared slides
PPTX
5th lec ofdm
PPTX
3rd lec fcss
PPTX
2nd lec wireless terminologies
PPTX
1st lec generations
PPT
4rth lec dsss
DOCX
Long questions
DOCX
Lecture notes on mobile communication
PPTX
Lecture5 mobile communication_short
PPT
8th lec flow and error control
PDF
Chapter 10:Risk and Refinements In Capital Budgeting
PDF
Chapter 9:Capital Budgeting Techniques
PDF
Chapter 5:Risk and Return
DOCX
Question and answer Programming
PDF
Email security &amp; threads
PPT
Chapter03 Top Down Design with Function
Bottom up parser
7th lec overview - latest
6th lec infrared slides
5th lec ofdm
3rd lec fcss
2nd lec wireless terminologies
1st lec generations
4rth lec dsss
Long questions
Lecture notes on mobile communication
Lecture5 mobile communication_short
8th lec flow and error control
Chapter 10:Risk and Refinements In Capital Budgeting
Chapter 9:Capital Budgeting Techniques
Chapter 5:Risk and Return
Question and answer Programming
Email security &amp; threads
Chapter03 Top Down Design with Function

Recently uploaded (20)

PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
01-Introduction-to-Information-Management.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Lesson notes of climatology university.
PDF
RMMM.pdf make it easy to upload and study
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Computing-Curriculum for Schools in Ghana
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Cell Structure & Organelles in detailed.
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Supply Chain Operations Speaking Notes -ICLT Program
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Pharma ospi slides which help in ospi learning
01-Introduction-to-Information-Management.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Renaissance Architecture: A Journey from Faith to Humanism
GDM (1) (1).pptx small presentation for students
Lesson notes of climatology university.
RMMM.pdf make it easy to upload and study
VCE English Exam - Section C Student Revision Booklet
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Computing-Curriculum for Schools in Ghana
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Abdominal Access Techniques with Prof. Dr. R K Mishra
Anesthesia in Laparoscopic Surgery in India
2.FourierTransform-ShortQuestionswithAnswers.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Cell Structure & Organelles in detailed.

Computation Chapter 4

  • 1. Chapter 4Chapter 4 ComputationComputation Bjarne StroustrupBjarne Stroustrup www.stroustrup.com/Programmingwww.stroustrup.com/Programming
  • 2. 22 AbstractAbstract  Today, I’ll present the basics of computation. InToday, I’ll present the basics of computation. In particular, we’ll discuss expressions, how toparticular, we’ll discuss expressions, how to iterate over a series of values (“iteration”), anditerate over a series of values (“iteration”), and select between two alternative actionsselect between two alternative actions (“selection”). I’ll also show how a particular sub-(“selection”). I’ll also show how a particular sub- computation can be named and specifiedcomputation can be named and specified separately as a function. To be able to performseparately as a function. To be able to perform more realistic computations, I will introduce themore realistic computations, I will introduce the vectorvector type to hold sequences of values.type to hold sequences of values.  Selection, Iteration, Function, VectorSelection, Iteration, Function, Vector Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 3. 33 OverviewOverview  ComputationComputation  What is computable? How best to compute it?What is computable? How best to compute it?  Abstractions, algorithms, heuristics, data structuresAbstractions, algorithms, heuristics, data structures  Language constructs and ideasLanguage constructs and ideas  Sequential order of executionSequential order of execution  Expressions and StatementsExpressions and Statements  SelectionSelection  IterationIteration  FunctionsFunctions  VectorsVectors Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 4. 44 You already know most of thisYou already know most of this  Note:Note:  You know how to do arithmeticYou know how to do arithmetic  d = a+b*cd = a+b*c  You know how to selectYou know how to select ““if this is true, do that; otherwise do something else ”if this is true, do that; otherwise do something else ”  You know how to “iterate”You know how to “iterate”  ““do this until you are finished”do this until you are finished”  ““do that 100 times”do that 100 times”  You know how to do functionsYou know how to do functions  ““go ask Joe and bring back the answer”go ask Joe and bring back the answer”  ““hey Joe, calculate this for me and send me the answer”hey Joe, calculate this for me and send me the answer”  What I will show you today is mostly just vocabulary andWhat I will show you today is mostly just vocabulary and syntax for what you already knowsyntax for what you already know Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 5. 55 ComputationComputation  Input: from keyboard, files, other input devices, other programs, otherInput: from keyboard, files, other input devices, other programs, other parts of a programparts of a program  Computation – what our program will do with the input to produce theComputation – what our program will do with the input to produce the output.output.  Output: to screen, files, other output devices, other programs, other partsOutput: to screen, files, other output devices, other programs, other parts of a programof a program (input) data (output) data data Code, often messy, often a lot of code Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 6. 66 ComputationComputation  Our job is to express computationsOur job is to express computations  CorrectlyCorrectly  SimplySimply  EfficientlyEfficiently  One tool is called Divide and ConquerOne tool is called Divide and Conquer  to break up big computations into many little onesto break up big computations into many little ones  Another tool is AbstractionAnother tool is Abstraction  Provide a higher-level concept that hides detailProvide a higher-level concept that hides detail  Organization of data is often the key to good codeOrganization of data is often the key to good code  Input/output formatsInput/output formats  ProtocolsProtocols  Data structuresData structures  Note the emphasis on structure and organizationNote the emphasis on structure and organization  You don’t get good code just by writing a lot of statementsYou don’t get good code just by writing a lot of statements Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 7. 77 Language featuresLanguage features  Each programming language feature exists to expressEach programming language feature exists to express a fundamental ideaa fundamental idea  For exampleFor example  ++ : addition: addition  ** : multiplication: multiplication  if (if (expressionexpression)) statementstatement elseelse statement ;statement ; selectionselection  while (while (expressionexpression)) statementstatement ;; iterationiteration  f(x);f(x); function/operationfunction/operation  ……  We combine language features to create programsWe combine language features to create programs Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 8. 88 ExpressionsExpressions //// compute area:compute area: int length = 20;int length = 20; //// the simplest expression: a literal (here, 20)the simplest expression: a literal (here, 20) //// (here used to initialize a variable)(here used to initialize a variable) int width = 40;int width = 40; int area = length*width;int area = length*width; //// a multiplicationa multiplication int average = (length+width)/2;int average = (length+width)/2; //// addition and divisionaddition and division The usual rules of precedence apply:The usual rules of precedence apply: a*b+c/da*b+c/d meansmeans (a*b)+(c/d)(a*b)+(c/d) and notand not a*(b+c)/da*(b+c)/d.. If in doubt, parenthesize. If complicated, parenthesize.If in doubt, parenthesize. If complicated, parenthesize. Don’t write “absurdly complicated” expressions:Don’t write “absurdly complicated” expressions: a*b+c/d*(e-f/g)/h+7a*b+c/d*(e-f/g)/h+7 //// too complicatedtoo complicated Choose meaningful names.Choose meaningful names. Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 9. 99 ExpressionsExpressions  Expressions are made out of operators and operandsExpressions are made out of operators and operands  Operators specify what is to be doneOperators specify what is to be done  Operands specify the data for the operators to work withOperands specify the data for the operators to work with  Boolean type:Boolean type: boolbool ((truetrue andand falsefalse))  Equality operators:Equality operators: = == = (equal),(equal), !=!= (not equal)(not equal)  Logical operators:Logical operators: &&&& (and),(and), |||| (or),(or), !! (not)(not)  Relational operators:Relational operators: << (less than),(less than), >> (greater than),(greater than), <=<=,, >=>=  Character type:Character type: charchar (e.g.,(e.g., 'a''a',, '7''7', and, and '@''@'))  Integer types:Integer types: short, int, longshort, int, long  arithmetic operators:arithmetic operators: +, -, *, /, %+, -, *, /, % (remainder)(remainder)  Floating-point types: e.g.,Floating-point types: e.g., float, doublefloat, double (e.g.,(e.g., 12.4512.45 andand 1.234e31.234e3))  arithmetic operators:arithmetic operators: +, -, *, /+, -, *, / Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 10. 1010 Concise OperatorsConcise Operators  For many binary operators, there are (roughly) equivalentFor many binary operators, there are (roughly) equivalent more concise operatorsmore concise operators  For exampleFor example  a += ca += c meansmeans a = a+ca = a+c  a *= scalea *= scale meansmeans a = a*scalea = a*scale  ++a++a meansmeans a += 1a += 1 oror a = a+1a = a+1  ““Concise operators” are generally better to useConcise operators” are generally better to use (clearer, express an idea more directly)(clearer, express an idea more directly) Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 11. 1111 StatementsStatements  A statement isA statement is  an expression followed by a semicolon, oran expression followed by a semicolon, or  a declaration, ora declaration, or  a “control statement” that determines the flow of controla “control statement” that determines the flow of control  For exampleFor example  a = b;a = b;  double d2 = 2.5;double d2 = 2.5;  if (x == 2) y = 4;if (x == 2) y = 4;  while (cin >> number) numbers.push_back(number);while (cin >> number) numbers.push_back(number);  int average = (length+width)/2;int average = (length+width)/2;  return x;return x;  You may not understand all of these just now, but you will …You may not understand all of these just now, but you will … Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 12. 1212 SelectionSelection  Sometimes we must select between alternativesSometimes we must select between alternatives  For example, suppose we want to identify the larger of twoFor example, suppose we want to identify the larger of two values. We can do this with anvalues. We can do this with an ifif statementstatement if (a<b)if (a<b) //// Note: No semicolon hereNote: No semicolon here max = b;max = b; elseelse //// Note: No semicolon hereNote: No semicolon here max = a;max = a;  The syntax isThe syntax is if (condition)if (condition) statement-1statement-1 //// if the condition is true, do statement-1if the condition is true, do statement-1 elseelse statement-2statement-2 //// if not, do statement-2if not, do statement-2 Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 13. 1313 Iteration (while loop)Iteration (while loop)  The world’s first “real program” running on a stored-programThe world’s first “real program” running on a stored-program computer (David Wheeler, Cambridge, May 6, 1949)computer (David Wheeler, Cambridge, May 6, 1949) //// calculate and print a table of squares 0-99:calculate and print a table of squares 0-99: int main()int main() {{ int i = 0;int i = 0; while (i<100) {while (i<100) { cout << i <<cout << i << ''tt'' << square(i) <<<< square(i) << ''nn'';; ++i ;++i ; //// incrementincrement ii }} }} //// (No, it wasn’t actually written in C++(No, it wasn’t actually written in C++ .).) Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 14. 1414 Iteration (while loop)Iteration (while loop)  What it takesWhat it takes  A loop variable (control variable);A loop variable (control variable); here:here: ii  Initialize the control variable;Initialize the control variable; here:here: int i = 0int i = 0  AA termination criterion;termination criterion; here: ifhere: if i<100i<100 is false, terminateis false, terminate  Increment the control variable;Increment the control variable; here:here: ++i++i  Something to do for each iteration;Something to do for each iteration; here:here: cout << …cout << … int i = 0;int i = 0; while (i<100) {while (i<100) { cout << i <<cout << i << ''tt'' << square(i) <<<< square(i) << ''nn'';; ++i ;++i ; //// incrementincrement ii }} Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 15. 1515 Iteration (for loop)Iteration (for loop)  Another iteration form: theAnother iteration form: the forfor looploop  You can collect all the control information in oneYou can collect all the control information in one place, at the top, where it’s easy to seeplace, at the top, where it’s easy to see for (int i = 0; i<100; ++i) {for (int i = 0; i<100; ++i) { cout << i <<cout << i << ''tt'' << square(i) <<<< square(i) << ''nn'';; }} That is,That is, for (for (initializeinitialize;; conditioncondition ;; incrementincrement )) controlled statementcontrolled statement Note: what isNote: what is square(i)square(i)?? Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 16. 1616 FunctionsFunctions  But what wasBut what was square(i)?square(i)?  A call of the functionA call of the function square()square() int square(int x)int square(int x) {{ return x*x;return x*x; }}  We define a function when we want to separate aWe define a function when we want to separate a computation because itcomputation because it  is logically separateis logically separate  makes the program text clearer (by naming the computation)makes the program text clearer (by naming the computation)  is useful in more than one place in our programis useful in more than one place in our program  eases testing, distribution of labor, and maintenanceeases testing, distribution of labor, and maintenance Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 17. 1717 Control FlowControl Flow int main()int main() {{ i=0;i=0; while (i<100)while (i<100) {{ square(i);square(i); }} }} int square(int x)int square(int x) {{ //// compute square rootcompute square root return x * x;return x * x; }}i<100 i==100 Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 18. 1818 FunctionsFunctions  Our functionOur function int square(int x)int square(int x) {{ return x*x;return x*x; }} is an example ofis an example of Return_type function_nameReturn_type function_name (( Parameter listParameter list )) //// (type name, etc.)(type name, etc.) {{ //// use each parameter in codeuse each parameter in code returnreturn some_valuesome_value;; //// ofof Return_typeReturn_type }} Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 19. 1919 Another ExampleAnother Example  Earlier we looked at code to find the larger of two values.Earlier we looked at code to find the larger of two values. Here is a function that compares the two values and returnsHere is a function that compares the two values and returns the larger value.the larger value. int max(int a, int b)int max(int a, int b) //// this function takes 2 parametersthis function takes 2 parameters {{ if (a<b)if (a<b) return b;return b; elseelse return a;return a; }} int x = max(7, 9);int x = max(7, 9); //// x becomes 9x becomes 9 int y = max(19, -27);int y = max(19, -27); //// y becomes 19y becomes 19 int z = max(20, 20);int z = max(20, 20); //// z becomes 20z becomes 20 Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 20. 2020 Data for Iteration - VectorData for Iteration - Vector  To do just about anything of interest, we need a collection ofTo do just about anything of interest, we need a collection of data to work on. We can store this data in adata to work on. We can store this data in a vectorvector. For example:. For example: //// read some temperatures into a vector:read some temperatures into a vector: int main()int main() {{ vector<double> temps;vector<double> temps; //// declare a vector of type double to storedeclare a vector of type double to store //// temperatures – like 62.4temperatures – like 62.4 double temp;double temp; //// a variable for a single temperature valuea variable for a single temperature value while (cin>>temp)while (cin>>temp) //// cin reads a value and stores it in tempcin reads a value and stores it in temp temps.push_back(temp);temps.push_back(temp); //// store the value of temp in the vectorstore the value of temp in the vector //// … do something …… do something … }} //// cin>>tempcin>>temp will return true until we reach the end of file or encounterwill return true until we reach the end of file or encounter //// something that isn’t a double: like the word “end”something that isn’t a double: like the word “end” Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 21. 2121 VectorVector  Vector is the most useful standard library data typeVector is the most useful standard library data type  aa vector<T>vector<T> holds an sequence of values of typeholds an sequence of values of type TT  Think of a vector this wayThink of a vector this way A vector namedA vector named vv contains 5 elements: {1, 4, 2, 3, 5}:contains 5 elements: {1, 4, 2, 3, 5}: 1 4 2 3 5 5v: v’s elements: v[0] v[1] v[2] v[3] v[4] size() Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 22. 2222 VectorsVectors vector<int> v;vector<int> v; //// start off emptystart off empty v.push_back(1);v.push_back(1); //// add an element with the valueadd an element with the value 11 v.push_back(4);v.push_back(4); //// add an element with the valueadd an element with the value 44 at end (“the back”)at end (“the back”) v.push_back(3);v.push_back(3); //// add an element with the valueadd an element with the value 33 at end (“the back”)at end (“the back”) v[0]v[0] v[1] v[2]v[1] v[2] 0v: 3 2 1 1 41 341 v: v: v: Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 23. 2323 VectorsVectors  Once you get your data into a vector you can easily manipulate itOnce you get your data into a vector you can easily manipulate it //// compute mean (average) and median temperatures:compute mean (average) and median temperatures: int main()int main() {{ vector<double> temps;vector<double> temps; //// temperatures in Fahrenheit, e.g. 64.6temperatures in Fahrenheit, e.g. 64.6 double temp;double temp; while (cin>>temp) temps.push_back(temp); //while (cin>>temp) temps.push_back(temp); // read and put into vectorread and put into vector double sum = 0;double sum = 0; for (int i = 0; i< temps.size(); ++i) sum += temps[i]; //for (int i = 0; i< temps.size(); ++i) sum += temps[i]; // sums temperaturessums temperatures cout << "Mean temperature: " << sum/temps.size() << 'n';cout << "Mean temperature: " << sum/temps.size() << 'n'; sort(temps);sort(temps); //// from std_lib_facilities.hfrom std_lib_facilities.h //// or sort(temps.begin(), temps.end();or sort(temps.begin(), temps.end(); cout << "Median temperature: " << temps[temps.size()/2] << 'n';cout << "Median temperature: " << temps[temps.size()/2] << 'n'; }} Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 24. 2424 Traversing a vectorTraversing a vector  Once you get your data into a vector you can easily manipulate itOnce you get your data into a vector you can easily manipulate it  Initialize with a listInitialize with a list  vector<int> v = { 1, 2, 3, 5, 8, 13 }; //vector<int> v = { 1, 2, 3, 5, 8, 13 }; // initialize with a listinitialize with a list  often we want to look at each element of a vector in turn:often we want to look at each element of a vector in turn: for (int i = 0; i< v.size(); ++i) cout << v[i] << 'n'; //for (int i = 0; i< v.size(); ++i) cout << v[i] << 'n'; // list all elementslist all elements //// there is a simpler kind of loop for that (a range-for loop):there is a simpler kind of loop for that (a range-for loop): for (int i : v) cout << x << 'n'; //for (int i : v) cout << x << 'n'; // list all elementslist all elements //// for each x in v …for each x in v … Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 25. 2525 Combining Language FeaturesCombining Language Features  You can write many new programs by combiningYou can write many new programs by combining language features, built-in types, and user-definedlanguage features, built-in types, and user-defined types in new and interesting ways.types in new and interesting ways.  So far, we haveSo far, we have  Variables and literals of typesVariables and literals of types bool, char, int, doublebool, char, int, double  vector, push_back(), [ ]vector, push_back(), [ ] (subscripting)(subscripting)  !=, ==, =, +, -, +=, <, &&, ||, !!=, ==, =, +, -, +=, <, &&, ||, !  max( ), sort( ), cin>>, cout<<max( ), sort( ), cin>>, cout<<  if, for, whileif, for, while  You can write a lot of different programs with theseYou can write a lot of different programs with these language features! Let’s try to use them in a slightlylanguage features! Let’s try to use them in a slightly different way…different way… Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 26. 2626 Example – Word ListExample – Word List //// “boilerplate” left out“boilerplate” left out vector<string> words;vector<string> words; for (string s; cin>>s && s != "quit“; )for (string s; cin>>s && s != "quit“; ) //// && means AND&& means AND words.push_back(s);words.push_back(s); sort(words);sort(words); //// sort the words we readsort the words we read for (string s : words)for (string s : words) cout << s << 'n';cout << s << 'n'; /*/* read a bunch of strings into a vector of strings, sortread a bunch of strings into a vector of strings, sort them into lexicographical order (alphabetical order),them into lexicographical order (alphabetical order), and print the strings from the vector to see what we have.and print the strings from the vector to see what we have. */*/ Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 27. 2727 Word list – Eliminate DuplicatesWord list – Eliminate Duplicates //// Note that duplicate words were printed multiple times. ForNote that duplicate words were printed multiple times. For //// example “the the the”. That’s tedious, let’s eliminate duplicates:example “the the the”. That’s tedious, let’s eliminate duplicates: vector<string> words;vector<string> words; for (string s; cin>>s && s!= "quit"; )for (string s; cin>>s && s!= "quit"; ) words.push_back(s);words.push_back(s); sort(words);sort(words); for (int i=1; i<words.size(); ++i)for (int i=1; i<words.size(); ++i) if(words[i-1]==words[i])if(words[i-1]==words[i]) ““get rid of words[i]” // (pseudocode)get rid of words[i]” // (pseudocode) for (string s : words)for (string s : words) cout << s << 'n';cout << s << 'n'; //// there are many ways to “get rid of words[i]”; many of them are messythere are many ways to “get rid of words[i]”; many of them are messy //// (that’s typical). Our job as programmers is to choose a simple clean(that’s typical). Our job as programmers is to choose a simple clean //// solution – given constraints – time, run-time, memory.solution – given constraints – time, run-time, memory. Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 28. 2828 Example (cont.) Eliminate Words!Example (cont.) Eliminate Words! //// Eliminate the duplicate words by copying only unique words:Eliminate the duplicate words by copying only unique words: vector<string> words;vector<string> words; for (string s; cin>>s && s!= "quit"; )for (string s; cin>>s && s!= "quit"; ) words.push_back(s);words.push_back(s); sort(words);sort(words); vector<string>w2;vector<string>w2; if (0<words.size()) {if (0<words.size()) { //// note style { }note style { } w2.push_back(words[0]);w2.push_back(words[0]); for (int i=1; i<words.size(); ++i) //for (int i=1; i<words.size(); ++i) // note: not a range-note: not a range-forfor if(words[i-1]!=words[i])if(words[i-1]!=words[i]) w2.push_back(words[i]);w2.push_back(words[i]); }} cout<< "found " << words.size()-w2.size() << " duplicatesn";cout<< "found " << words.size()-w2.size() << " duplicatesn"; for (string s : w2)for (string s : w2) cout << s << "n";cout << s << "n"; Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 29. 2929 AlgorithmAlgorithm  We just used a simple algorithmWe just used a simple algorithm  An algorithm is (from Google search)An algorithm is (from Google search)  ““a logical arithmetical or computational procedure that, if correctlya logical arithmetical or computational procedure that, if correctly applied, ensures the solution of a problem.” –applied, ensures the solution of a problem.” – Harper CollinsHarper Collins  ““a set of rules for solving a problem in a finite number of steps, as fora set of rules for solving a problem in a finite number of steps, as for finding the greatest common divisor.” –finding the greatest common divisor.” – Random HouseRandom House  ““a detailed sequence of actions to perform or accomplish some task.a detailed sequence of actions to perform or accomplish some task. Named after an Iranian mathematician, Al-Khawarizmi. Technically, anNamed after an Iranian mathematician, Al-Khawarizmi. Technically, an algorithm must reach a result after a finite number of steps, …The term isalgorithm 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 notalso used loosely for any sequence of actions (which may or may not terminate).” –terminate).” – Webster’sWebster’s  We eliminated the duplicates by first sorting the vectorWe eliminated the duplicates by first sorting the vector (so that duplicates are adjacent), and then copying only(so that duplicates are adjacent), and then copying only strings that differ from their predecessor into anotherstrings that differ from their predecessor into another vector.vector. Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 30. 3030 IdealIdeal  Basic language features and libraries should beBasic language features and libraries should be usable in essentially arbitrary combinations.usable in essentially arbitrary combinations.  We are not too far from that ideal.We are not too far from that ideal.  If a combination of features and types make sense,If a combination of features and types make sense, it will probably work.it will probably work.  The compiler helps by rejecting some absurdities.The compiler helps by rejecting some absurdities. Stroustrup/Programming/2015Stroustrup/Programming/2015
  • 31. 3131 The next lectureThe next lecture  How to deal with errorsHow to deal with errors Stroustrup/Programming/2015Stroustrup/Programming/2015