Bjarne Stroustrup www.stroustrup.com/Programming Chapter 4 Computation Bjarne Stroustrup www.stroustrup.com/Programming.

Slides:



Advertisements
Similar presentations
Chapter 4 Computation Bjarne Stroustrup
Advertisements

Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Computer Science 1620 Programming & Problem Solving.
Data types and variables
C++ Programming Language Day 1. What this course covers Day 1 – Structure of C++ program – Basic data types – Standard input, output streams – Selection.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Input, Output, and Processing
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Working with Batches of Data Lecture 4 Hartmut Kaiser
Looping and Counting Lecture 3 Hartmut Kaiser
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Bill Tucker Austin Community College COSC 1315
The Ohio State University
Chapter 3 Selection Statements
Repetitive Structures
Chapter Topics The Basics of a C++ Program Data Types
Topics Designing a Program Input, Processing, and Output
Chapter 3 Control Statements
Chapter 7: Expressions and Assignment Statements
Chapter 1: Introduction to computers and C++ Programming
Introduction to C++ Programming
Chapter 2 Introduction to C++ Programming
Chapter 2: Introduction to C++
Computing and Statistical Data Analysis Lecture 2
Computing Fundamentals
Basic Elements of C++.
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 7: Expressions and Assignment Statements
The Selection Structure
Bjarne Stroustrup Chapter 4 Computation Bjarne Stroustrup
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 2: Introduction to C++
Basic Elements of C++ Chapter 2.
Modification of Slides by
Chapter 4: Control Structures I (Selection)
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is legal identifier? what.
2.1 Parts of a C++ Program.
Introduction to C++ Programming
Programming Funamental slides
Chapter 7 Additional Control Structures
Programming Funamental slides
Introduction to C++ Programming
Bjarne Stroustrup Chapter 4 Computation Bjarne Stroustrup
Chapter 4: Control Structures I (Selection)
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Chapter 2: Introduction to C++.
Boolean Expressions to Make Comparisons
C++ Programming Lecture 3 C++ Basics – Part I
Topics Designing a Program Input, Processing, and Output
Fundamental Programming
Summary of what we learned yesterday
Topics Designing a Program Input, Processing, and Output
Chapter 4 Computation Bjarne Stroustrup
C++ Programming Basics
Bjarne Stroustrup Chapter 4 Computation Bjarne Stroustrup
C++ for Engineers and Scientists Second Edition
Chapter 1 c++ structure C++ Input / Output
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Presentation transcript:

Bjarne Stroustrup www.stroustrup.com/Programming Chapter 4 Computation Bjarne Stroustrup www.stroustrup.com/Programming

Abstract basics of computation Selection, Iteration, Function, Vector Expressions select between two alternative actions (“selection”) how to iterate over a series of values (“iteration”) I’ll also show how a particular sub-computation can be named and specified separately as a function. To be able to perform more realistic computations, I will introduce the vector type to hold sequences of values. Selection, Iteration, Function, Vector Stroustrup/Programming

Overview Computation Language constructs and ideas 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 Iteration Functions Vectors Stroustrup/Programming

Computation Code, often messy, often a lot of code (input) data (output) data data Input: from keyboard, files, other input devices, other programs, other parts of a program Computation – what our program will do with the input to produce the output. Output: to screen, files, other output devices, other programs, other parts of a program Stroustrup/Programming

Computation Our job is to express computations Correctly Simply Efficiently One tool is called abstraction, which provides a higher-level concept that hides detail cin is an abstraction of keyboard device Device driver handles details about hardware interrupt, buffering, … cout data type such as int, double, are abstractions of memory Stroustrup/Programming

Computation (cont’d) One tool is called Divide and Conquer to break up big computations into many smaller ones Like assembly line, organization, building lego toys Organization of data is often the key to good code Input/output formats Protocols Data structures A pizza restaurant system that keeps all transaction records Note the emphasis on structure and organization You don’t get good code just by writing a lot of statements Stroustrup/Programming

Language features Each programming language feature exists to express a fundamental idea + : addition * : multiplication if (expression) statement else statement ; selection while (expression) statement ; iteration f(x); function/operation … We combine language features to create programs Stroustrup/Programming

You already know most of this You know how to do arithmetic d = a+b*c You know how to select “if this is true, do that; otherwise do something else ” You know how to “iterate” “do this until you are finished” “do that 100 times” You know how to do functions “go ask Joe and bring back the answer” “hey Joe, calculate this for me and send me the answer” What we learn here is mostly just vocabulary and syntax for what you already know Stroustrup/Programming

Expressions An expression computes a value from a number of operands Most basic building block of programs Simplest expression: a literal value, name of variables 10, ‘a’, 3.24, “Hello world!\n” total_due, change, … More complicated expressions: made out of operators and operands Operators specify what is to be done, +, *, =, /, … Operands specify the data for the operators to work with Stroustrup/Programming

Expressions // compute area: int length = 20; // the simplest expression: a literal (here, 20) // (here used to initialize a variable) int width = 40; int area = length*width; // a multiplication int average = (length+width)/2; // addition and division The usual rules of precedence apply: a*b+c/d means (a*b)+(c/d) and not 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 Choose meaningful names. Stroustrup/Programming

Constant expressions Three types of constant expressions: literal value, named constant, an expression with only constant operands 3.1415, 15.39, 19.39 const double PRICE_12_PIZZA = 15.39; double total = num12*PRICE_12_PIZZA + num14*PRICE_14_PIZZA; const int max=18; max+2; //this is a constant expression Stroustrup/Programming

Assignment expression int average=20; average = average/2; average on left-hand side and right-hand side of = interpreted differently Left-hand: means “the object named average”, “lvalue of average” Right-hand: means “the value of the object named by average”, “the value of average”, “rvalue of average” Left-hand operand of assignment operator, =, needs to be a variable 10=a; // compilation error “error: lvalue required as left operand of assignment” Stroustrup/Programming

Data types & OPERATORS Integer types: short, int, long Arithmetic operators: +, -, *, /, % (remainder) Relational operators: < (less than), > (greater than), <=, >= Floating-point types: e.g., float, double (e.g., 12.45 and 1.234e3) arithmetic operators: +, -, *, / Boolean type: bool (true and false) Equality operators: = = (equal), != (not equal) Logical operators: && (and), || (or), ! (not) Character type: char (e.g., 'a', '7', and '@') Stroustrup/Programming

Integer division and module operation Integer types: short, int, long Arithmetic operators: +, -, *, /, % (remainder) All above operations evaluate to an integer 4/3, 123 % 2, … Integer division: fraction part is thrown away 4/3 = 1 23/45 = 0 Module operator: % a%b evaluates to the remainder when a is divided by b 5 % 2 is 1 , 4 % 2 is 0 23 % 10 is 3 ,… Stroustrup/Programming

Integer/float arithmetic Fahrenheit to Celsius (°F - 32) x 5/9 => °C How to implement it in C++ code? Stroustrup/Programming

Exercises What’s the value of the following expressions? 1.0+13/4 , (1.0+13)/4 123 % 10 How to express using C++? double x1= double x2= Recall function sqrt(t) return square root of t How to find the 10th digit of an integer? E.g., 10th digit of 342 is 4 Stroustrup/Programming

Concise Operators For many binary operators, there are (roughly) equivalent more concise operators For example a += c means a = a+c a *= scale means a = a*scale ++a means a += 1 or a = a+1 “Concise operators” are generally better to use (clearer, express an idea more directly) Stroustrup/Programming

Note: = is used for assignment Comparison operators Used to compare numbers and strings, evaluate to a bool value (true or false) C++ Math Notation Description >> > Greater than, >= ≥ Greater than or equal < < Less than <= ≤ Less than or equal == = Equal != ≠ Not equal Note: = is used for assignment == tests for equality Stroustrup/Programming

Data types & OPERATORS Integer types: short, int, long Arithmetic operators: +, -, *, /, % (remainder) Relational operators: < (less than), > (greater than), <=, >=, ==, != Floating-point types: e.g., float, double (e.g., 12.45 and 1.234e3) arithmetic operators: +, -, *, / Boolean type: bool (true and false) Logical/Boolean operators: && (and), || (or), ! (not) Character type: char (e.g., 'a', '7', and '@') Stroustrup/Programming

Data Type: bool an bool variable has two possible value: true or false Useful for storing a value to be used later: bool discounted = (country == "USA" && weight <= 1); ... if (discounted) ... Also makes the code more legible Stroustrup/Programming

Data Type: bool in C++ any nonzero value “evaluates” to true if (n) // if (n!=0) cout << “n is not zero \n”; Don't do this: if (x = 7) ... // a logic error! Will always be true x will have the value 7 afterwards Stroustrup/Programming

Boolean Operations Boolean operators (after George Boole) have Boolean expressions as operands combine conditions into larger, more complex Boolean expressions Two binary operators: && logical and || Logical or One uniary operators: ! Logic not Stroustrup/Programming

Boolean Operations (examples) Following test is true only when both country is "USA", and the weight is < 1 if (country == "USA" && weight <= 1) shipping_charge = 2.50; following test is true if state is either "HI" or "AK": if (state == "HI" || state == "AK") shipping_charge = 10.00; Stroustrup/Programming

Boolean Operations (not operator) The ! operator (said "not") inverts the value of a Boolean expression (unary operator) ! (n==0) is the same as (n!=0) ! (n>=0) is same as (n<0) ! (k>m) is same as ? Prefer the simpler expressions Stroustrup/Programming

Common Error: Multiple Relational Operators x=-10.0; if (-0.5 <= x <= 2.5) // a logic error Makes sense in mathematics, testing whether x falls within the range C++ interprets it as follows: -0.5 <= x evaluates to true (1) or false (0) Compare Boolean value to double value of 2.5, always true Needs to be done this way: if (-0.5 <= x && x <= 0.5) ... Stroustrup/Programming

Boolean Operations (summary) A && B true false A B A || B true false A !A True False true Stroustrup/Programming

Boolean Operations (lazy evaluation) && and || operators are evaluated lazily Operands are evaluated left-to-right Evaluation ends as soon as the truth value is determined Given X is true and Y is false: X || Y is true; Y is not evaluated (there is no need …) Y && X is false; X is not evaluated This is quite handy: (n > 0) && (tot/n < 0.9) Stroustrup/Programming

Exercise What the value of following boolean expression? int x=10; bool b1 = (x % 2 == 0); bool b2 = (x>10 || x!=2); bool b3 = ( (x-2)<8 ); Stroustrup/Programming

Statements A statement is an expression followed by a semicolon, a = b; a declaration, double d2 = 2.5; a “control statement” that determines the flow of control 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

Selection Sometimes we must specify a conditional process if number of 12-inch pizzas is greater than 0 , display the number and price if (num12 > 0) cout <<″12-inch pizza\t\t″ <<num12<<″\t″ <<num12*PRICE_12_PIZZA <<″\n″; Syntax is if (condition) statement //statement is executed only if condition is true true condition statement false Next statement in program Stroustrup/Programming

Selection if (a<b) // Note: No semicolon here select between alternatives E.g, to identify larger of two values: if (a<b) // Note: No semicolon here max = b; else // Note: No semicolon here max = a; syntax is if (condition) statement-1 // if condition is true, do statement-1 else statement-2 // if not, do statement-2 false true condition Statement-1 Statement-2 Next statement in program Stroustrup/Programming

Block statement if (condition) statement //if condition is true, do statement statement-1 // if condition is true, do statement-1 else statement-2 // if not, do statement-2 Statement can be a block statement, i.e., a sequence of statements enclosed by { and } if (num_12 < 0) { cout <<“Invalid input\n”; return -1; //exit the program with a -1 return value } Stroustrup/Programming

Next half Stroustrup/Programming

Rules of operator precedence Operators in parentheses evaluated first Nested/embedded parentheses Operators in innermost pair first Multiplication, division, modulus applied next Operators applied from left to right Addition, subtraction applied last CS1600 Xiaolan Zhang Fall 2010

Programming errors Syntax errors (or compilation errors) Mistyping a keyword Variables not declared Missing semicolons, … Runtime errors Not captured by compiler, execution aborted E.g. divide by zero, accessing wrong memory location, … Avoid them by checking input, … Logic errors Program executed normally to the end, but outcome is wrong E.g. int area = r*r*3.1415;

Question Question : Which statement is correct , A or B ? int integerOne = 1; double doubleOne = 2.5; int sumOne = integerOne + doubleOne; //A double sumTwo = integerOne + doubleOne; //B Which statement is correct , A or B ? CS1600 Xiaolan Zhang

Output Statement With Expression Variables or expressions could be inserted into output statement, its value is printed out. Long output statement could be broken into multiple lines. Example: std::cout << “sum is ” << sum << “. bye-bye! \n”; std::cout << “sum is ” << number1 + number2 ; CS1600 Xiaolan Zhang

INT, double, float, … Stroustrup/Programming

Data type int Representing whole numbers, i.e., those numbers that have no decimal parts For counting number of people, classrooms, stars,… In C/C++, int data type is 4 byte long (32 bits) Can store values from -2,147,483,648 to 2,147,483,647 long long: 8 byte long (64 bits) -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Floating point type For storing values with decimal parts, real values E.g., 3.1415, 15.39, 0.3333333333333, sqrt(2), C/C++ provides two floating point type: float and double float: usually 32 bits long Can store values within range: 3.4 e-38, 3.4e+38 has a precision of 7 digits type double: 64 bits long Can store value within range: 1.7e308, 1.7e308 15 digits precision Stroustrup/Programming

If change double to float, #include <iostream> #include <iomanip> using namespace std; int main() { double a=1.2345678e10; // the literal constant has 8 significant digits cout <<"a=" << setprecision(10) << a<<endl; } Output: a=1.2345678e+10 //double can represent the value accurately If change double to float, a=1.234567782e+10 //float cannot Stroustrup/Programming

#include <iomanip> int main() { double a; int n; cout <<"Enter a:"; cin >> a; cout <<"a's value is " << a << “\n"; } test_double.cpp Try following input: 30, output 30 30.00, output 30 2e310, output 1.79769e+308 1.234567890123456789, output 1.23457 Value overflow! By default, cout outputs a double value with up to 6 significant digits Stroustrup/Programming

double data type represents a number If enter value 1.234567890123456789 output: 1.2345678901234566904 If value entered is: 0.00000001234567890123456789 output is: 1.23456789012345674501e-08 123456789012345678900000000 output is : 1.23456789012345678153e+26 2.1234567890000000000000 2.123456789000000011213842299185e+00 double data type represents a number approximately, the precision is 15 significant digits. (sometimes you get lucky ). #include <iomanip> int main() { double a; cout <<"Enter a:"; cin >> a; cout <<"a's value is " << setprecision (20) // display value up to 20 // significant digits << a <<"\n"; } test_double2.cpp Stroustrup/Programming

Significant digits Significant digits of a number: digits that carry meaning contributing to its precision. this includes all digits except leading zeros  double data type guarantees to represents a number accurately up to 15 significant digits, i.e., it has a precision of 15 float data type guarantees to represents a number accurately up to 7 significant digits, i.e., it has a precision of 7 long double … Stroustrup/Programming

significant DIGITS All non-zero digits are considered significant. 91 has two (9 and 1), while 123.45 has five (1, 2, 3, 4 and 5). Zeros appearing between two non-zero digits are significant 101.12 has five: 1, 0, 1, 1 and 2. Leading zeros are not significant 0.00052 has two significant figures: 5 and 2. Trailing zeros in a number are significant. 12.2300 has six : 1, 2, 2, 3, 0 and 0. 0.000122300 still has only six (the zeros before the 1 are not significant) 120.00 has five significant figures 12.23 vs 12.2300 Stroustrup/Programming

Precision of floating type Precision: the number of significant digits the data type can store without loss of information E.g. 0.3333333333333333333…33 There are 100 number of 3. Both double and type use finite amount of memory, cannot store all possible real value exactly

Output: If change to float type, #include <iostream> #include <iomanip> using namespace std; int main() { double a=1.2345678e10; // the literal constant has 8 significant digits cout <<"a=" << setprecision(10) << a<<endl; } Output: a=1.2345678e+10 //double can represent the value accurately If change to float type, a=1.234567782e+10 //float cannot Stroustrup/Programming

[zhang@storm Codes]$ ./a.out double change=40.0-15.38*1; cout <<"change due" << fixed <<change<<endl; int d= change; cout <<"d=" << d <<endl; int q = (change-d)/0.25; cout <<"q=" << q <<endl; int dm = (change-d-q*0.25)/0.1; cout <<"dm=" << dm <<endl; int n = (change-d-q*0.25-dm*0.1)/0.05; cout <<"n=" << n <<endl; int p = (change-d-q*0.25-dm*0.1-n*0.05)/0.01; cout <<"Right hand side" << setprecision(15) << fixed << (change-d-q*0.25-dm*0.1-n*0.05)/0.01 <<endl; cout <<"p=" << p <<endl; Give Change problem [zhang@storm Codes]$ ./a.out change due 24.620000 d=24 q=2 dm=1 n=0 Right hand side1.999999999999744 p=1 Stroustrup/Programming

49 Solution Better solution: use int to store money amount (measured in cents) #include <math.h> int dollar = floor(change); int p = round(change-d-q*0.25-dm*0.1-n*0.05)/0.01; int cents = round(change); floor(double x): return the largest integral value that is not greater than x round (double x): round x to the nearest integer round (0.5)=1, round (56.0)=56

Back to selection statement, i.e., IF/else statement Stroustrup/Programming

Nested Branches Often necessary to nest an if/else statement inside another, to decide across several categories Stroustrup/Programming

Demo Write embedded if/else statements Exercise Leap year testing logic Stroustrup/Programming

Multiple alternative if (richter>=8.0) cout <<“most structure fall\n”; else { if (richter>=7.0) cout <<“Many buildings destroyed\n”; else { if (richter >=6.0) cout <<“Many building consi…\n”; if (richter>=4.5) cout <<“damage to ..\n”; } cout <<“No des…\n”; Stroustrup/Programming

Multiple alternative if (richter>=8.0) if (richter>=8.0) cout <<“most structure fall\n”; else if (richter>=7.0) cout <<“Many buildings destroyed\n”; if (richter >=6.0) cout <<“Many building consi…\n”; if (richter>=4.5) cout <<“damage to ..\n”; cout <<“No des…\n”; if (richter>=8.0) cout <<“most structure fall\n”; else { if (richter>=7.0) cout <<“Many buildings destroyed\n”; else { if (richter >=6.0) cout <<“Many building consi…\n”; if (richter>=4.5) cout <<“damage to ..\n”; } cout <<“No des…\n”; Stroustrup/Programming

Multiple alternatives if (richter >= 8.0) cout << "Most structures fall"; else if (richter >= 7.0) cout << "Many buildings destroyed"; else if (richter >= 6.0) cout << "Many buildings …"; else if (richter >= 4.5) cout << "Damage to …"; else cout << "Generally no damage"; if (richter>=8.0) cout <<“most structure fall\n”; else if (richter>=7.0) cout <<“Many buildings destroyed\n”; if (richter >=6.0) cout <<“Many building consi…\n”; if (richter>=4.5) cout <<“damage to ..\n”; cout <<“No des…\n”; Stroustrup/Programming

Exercise Implement a menu selection, where program prompt user to select diff. action based on input: Enter a simple arithmetic expression (+,-,*,/,%): 12+34 Result is: 36 Hint: char op; cin >> num1 >> op >> num2; //test whether op is equal to ‘+’, ‘-’,’*’,’/’. Stroustrup/Programming

Summary Expression, operators Statement Declaration statement Expression statement if statement, return statement cout, cin, statement Difference between expression and statement? Statement ends with ; Expression can be used in cout cout <<“Total is: “ << n1*p1+n2*p2 <<“\n”; cout <<“total is: “ << double total <<“\n”; //not an expression Stroustrup/Programming

Iteration (while loop) The world’s first “real program” running on a stored- program computer (David Wheeler, Cambridge, May 6, 1949) // calculate and print a table of squares 0-99: int main() { int i = 0; while (i<100) { cout << i << '\t' << square(i) << '\n'; ++i ; // increment i } // (No, it wasn’t actually written in C++ .) Stroustrup/Programming

Iteration (while loop) What it takes A loop variable (control variable); here: i Initialize the control variable; here: int i = 0 A termination criterion; here: if i<100 is false, terminate Increment the control variable; here: ++i Something to do for each iteration; here: cout << … int i = 0; while (i<100) { cout << i << '\t' << square(i) << '\n'; ++i ; // increment i } Stroustrup/Programming

Iteration (for loop) Another iteration form: for loop You can collect all the control information in one place, at the top, where it’s easy to see for (int i = 0; i<100; ++i) { cout << i << '\t' << square(i) << '\n'; } That is, for (initialize; condition ; increment ) controlled statement Note: what is square(i)? Stroustrup/Programming

Functions But what was square(i)? A call of the function square() int square(int x) { return x*x; } We define a function when we want to separate a computation because it 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

Control Flow int main() { i=0; while (i<100) square(i) } int square(int x) { return x * x; } i<100 i==100 Stroustrup/Programming

Functions is an example of Our function int square(int x) { return x*x; } is an example of Return_type function_name ( Parameter list ) // (type name, etc.) // use each parameter in code return some_value; // of Return_type Stroustrup/Programming

Another Example Earlier we looked at code to find the larger of two values. 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 { if (a<b) return b; else return a; } int x = max(7, 9); // x becomes 9 int y = max(19, -27); // y becomes 19 int z = max(20, 20); // z becomes 20 Stroustrup/Programming

Data for Iteration - Vector To do just about anything of interest, we need a collection of data to work on. We can store this data in a vector. For example: // read some temperatures into a vector: int main() { vector<double> temps; // declare a vector of type double to store // temperatures – like 62.4 double temp; // a variable for a single temperature value while (cin>>temp) // cin reads a value and stores it in temp temps.push_back(temp); // store the value of temp in the vector // … do something … } // cin>>temp will return true until we reach the end of file or encounter // something that isn’t a double: like the word “end” Stroustrup/Programming

Vector Vector is the most useful standard library data type v: 5 1 4 2 a vector<T> holds an sequence of values of type T Think of a vector this way A vector named v contains 5 elements: {1, 4, 2, 3, 5}: size() v: 5 v[0] v[1] v[2] v[3] v[4] 1 4 2 3 5 v’s elements: Stroustrup/Programming

Vectors vector<int> v; // start off empty v.push_back(1); // add an element with the value 1 v.push_back(4); // add an element with the value 4 at end (“the back”) v.push_back(3); // add an element with the value 3 at end (“the back”) v[0] v[1] v[2] v: 1 1 v: 2 1 4 v: 3 1 4 3 v: Stroustrup/Programming

Vectors Once you get your data into a vector you can easily manipulate it: // compute mean (average) and median temperatures: int main() { vector<double> temps; // temperatures in Fahrenheit, e.g. 64.6 double temp; while (cin>>temp) temps.push_back(temp); // read and put into vector double sum = 0; for (int i = 0; i< temps.size(); ++i) sum += temps[i]; // sums temperatures cout << "Mean temperature: " << sum/temps.size() << endl; sort(temps.begin(),temps.end()); cout << "Median temperature: " << temps[temps.size()/2] << endl; } Stroustrup/Programming

Combining Language Features You can write many new programs by combining language features, built-in types, and user-defined types in new and interesting ways. So far, we have Variables and literals of types bool, char, int, double vector, push_back(), [ ] (subscripting) !=, ==, =, +, -, +=, <, &&, ||, ! max( ), sort( ), cin>>, cout<< if, for, while You can write a lot of different programs with these language features! Let’s try to use them in a slightly different way… Stroustrup/Programming

Example – Word List // “boilerplate” left out vector<string> words; string s; while (cin>>s && s != "quit") // && means AND words.push_back(s); sort(words.begin(), words.end()); // sort the words we read for (int i=0; i<words.size(); ++i) cout<<words[i]<< "\n"; /* read a bunch of strings into a vector of strings, sort them into lexicographical order (alphabetical order), and print the strings from the vector to see what we have. */ Stroustrup/Programming

Word list – Eliminate Duplicates // Note that duplicate words were printed multiple times. For // example “the the the”. That’s tedious, let’s eliminate duplicates: vector<string> words; string s; while (cin>>s && s!= "quit") words.push_back(s); sort(words.begin(), words.end()); for (int i=1; i<words.size(); ++i) 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 // (that’s typical). Our job as programmers is to choose a simple clean // solution – given constraints – time, run-time, memory. Stroustrup/Programming

Example (cont.) Eliminate Words! // Eliminate the duplicate words by copying only unique words: vector<string> words; 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 { } w2.push_back(words[0]); for (int i=1; i<words.size(); ++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

Algorithm We just used a simple algorithm An algorithm is (from Google search) “a logical arithmetical or computational procedure that, if correctly applied, ensures the solution of a problem.” – Harper Collins “a set of rules for solving a problem in a finite number of steps, as for finding the greatest common divisor.” – Random House “a detailed sequence of actions to perform or accomplish some task. 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 (so that duplicates are adjacent), and then copying only strings that differ from their predecessor into another vector. Stroustrup/Programming

Ideal Basic language features and libraries should be usable in essentially arbitrary combinations. We are not too far from that ideal. If a combination of features and types make sense, it will probably work. The compiler helps by rejecting some absurdities. Stroustrup/Programming

The next lecture How to deal with errors Stroustrup/Programming