b4185c3c19d65798d3785ab672f161f1.ppt
- Количество слайдов: 75
Bjarne Stroustrup www. stroustrup. com/Programming
basics of computation Expressions select between two alternative actions (“selection”) how to iterate over a series of values (“iteration”) I’ll also show 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 2
Computation What is computable? How best to compute it? Abstractions, algorithms, heuristics, data structures Language constructs and ideas Sequential order of execution Expressions and Statements Selection Iteration Functions Vectors Stroustrup/Programming 3
Code, often messy, (input) data often a lot of code (output) 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 4
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 5
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 6
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 7
You know how to do arithmetic d = a+b*c You know how to select You know how to “iterate” “if this is true, do that; otherwise do something else ” “do this until you are finished” “do that 100 times” “go ask Joe and bring back the answer” “hey Joe, calculate this for me and send me the answer” You know how to do functions What we learn here is mostly just vocabulary and syntax for what you already know Stroustrup/Programming 8
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 9
// 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; int average = (length+width)/2; // a multiplication // 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 10
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 = num 12*PRICE_12_PIZZA + num 14*PRICE_14_PIZZA; const int max=18; max+2; //this is a constant expression Stroustrup/Programming 11
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 12
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. 234 e 3) arithmetic operators: +, -, *, / Relational operators: < (less than), > (greater than), <=, >= 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 13
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 14
Fahrenheit to Celsius (°F - 32) x 5/9 => °C How to implement it in C++ code? Stroustrup/Programming 15
What’s the value of the following expressions? 1. 0+13/4 , (1. 0+13)/4 123 % 10 How to express using C++? double x 1= double x 2= Recall function sqrt(t) return square root of t How to find the 10 th digit of an integer? E. g. , 10 th digit of 342 is 4 Stroustrup/Programming 16
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 17
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 18
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. 234 e 3) arithmetic operators: +, -, *, / Relational operators: < (less than), > (greater than), <=, >=, ==, != Boolean type: bool (true and false) Logical/Boolean operators: && (and), || (or), ! (not) Character type: char (e. g. , 'a', '7', and '@') Stroustrup/Programming 19
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 20
in C++ any nonzero value “evaluates” to true n=10; 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 21
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 22
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 or "AK": test is true if state is either "HI" if (state == "HI" || state == "AK") shipping_charge = 10. 00; Stroustrup/Programming 23
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 24
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 25
A B A && B true false true false A B A || B A !A true True False true false true false Stroustrup/Programming 26
&& 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 27
What the value of following boolean expression? int x=10; bool b 1 = (x % 2 == 0); bool b 2 = (x>10 || x!=2); bool b 3 = ( (x-2)<8 ); Stroustrup/Programming 28
A statement is an expression followed by a semicolon, a = b; a declaration, double d 2 = 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 29
Sometimes we must specify a conditional process if number of 12 -inch pizzas is greater than 0 , display the number and price if (num 12 > 0) cout <<″ 12 -inch pizzatt″ <<num 12<<″t″ <<num 12*PRICE_12_PIZZA <<″n″; condi tion true statement false Syntax is if (condition) statement //statement is executed only if condition is true Stroustrup/Programming Next statement in program 30
select between alternatives E. g, to identify larger of two values: if (a<b) max = else max = // Note: No semicolon here b; // Note: No semicolon here a; false Statement-2 syntax is condi tion true Statement-1 Next statement in program if (condition) statement-1 // if condition is true, do statement-1 else statement-2 // if not, do statement-2 Stroustrup/Programming 31
if (condition) statement //if condition is true, do statement if (condition) 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 inputn”; return -1; //exit the program with a -1 return value } Stroustrup/Programming 32
Stroustrup/Programming 33
Operators in parentheses evaluated first Nested/embedded parentheses Operators in innermost pair first Multiplication, next Operators applied from left to right Addition, division, modulus applied subtraction applied last Operators applied from left to right CS 1600 Xiaolan Zhang Fall 2010 34
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 : integer. One = 1; double. One = 2. 5; int sum. One = integer. One + double. One; //A double sum. Two = integer. One + double. One; //B Which statement is correct , A or B ? CS 1600 Xiaolan Zhang 36
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 ” << number 1 + number 2 ; CS 1600 Xiaolan Zhang 37
Stroustrup/Programming 38
INT Representing whole numbers, i. e. , those numbers that have no decimal parts For counting number of people, classrooms, stars, … In int data type is 4 byte long (32 bits) C/C++, Can store values from -2, 147, 483, 648 to 2, 147, 483, 647 long: 8 byte long (64 bits) -9, 223, 372, 036, 854, 775, 808 to 9, 223, 372, 036, 854, 775, 807
For storing values with decimal parts, real values E. g. , 3. 1415, 15. 39, 0. 3333333, 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. 4 e+38 has a precision of 7 digits type double: 64 bits long Can store value within range: 1. 7 e 308, 1. 7 e 308 15 digits precision Stroustrup/Programming 40
#include <iostream> #include <iomanip> using namespace std; int main() { double a=1. 2345678 e 10; // the literal constant has 8 significant digits cout <<"a=" << setprecision(10) << a<<endl; } Output: a=1. 2345678 e+10 //double can represent the value accurately If change double to float, a=1. 234567782 e+10 //float cannot Stroustrup/Programming 41
#include <iomanip> int main() test_double. cpp { double a; int n; cout <<"Enter a: "; cin >> a; cout <<"a's value is " << a << “n"; } Try following input: • 30, output 30 • 30. 00, output 30 • 2 e 310, output 1. 79769 e+308 • 1. 234567890123456789, output 1. 23457 Stroustrup/Programming Value overflow! By default, cout outputs a double value with up to 6 significant digits 42
If enter value 1. 234567890123456789 output: 1. 2345678901234566904 If value entered is: 0. 0000000123456789 output is: 1. 23456789012345674501 e-08 #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_double 2. cpp If value entered is: 12345678900000000 output is : 1. 23456789012345678153 e+26 If value entered is: 2. 1234567890000000 output is: 2. 12345678900000001121384229918 5 e+00 double data type represents a number approximately, the precision is 15 significant digits. (sometimes you get lucky ). Stroustrup/Programming 43
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 44
All non-zero digits are considered significant. Zeros appearing between two non-zero digits are significant 101. 12 has five: 1, 0, 1, 1 and 2. Leading zeros are not significant 91 has two (9 and 1), while 123. 45 has five (1, 2, 3, 4 and 5). 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. 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 45
PRECISION Precision: the number of significant digits the data type can store without loss of information E. g. 0. 3333333333… 33 There are 100 number of 3. Both double and type use finite amount of memory, cannot store all possible real value exactly
#include <iostream> #include <iomanip> using namespace std; int main() { double a=1. 2345678 e 10; // the literal constant has 8 significant digits cout <<"a=" << setprecision(10) << a<<endl; } Output: a=1. 2345678 e+10 //double can represent the value accurately If change to float type, a=1. 234567782 e+10 //float cannot Stroustrup/Programming 47
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; [zhang@storm Codes]$. /a. out change due 24. 620000 d=24 q=2 dm=1 n=0 Right hand side 1. 99999974 p=1 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; Stroustrup/Programming 48
49 #include <math. h> int dollar = floor(change); Better solution: use int to store money amount (measured in cents) 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
Stroustrup/Programming 50
Often necessary to nest an if/else statement inside another, to decide across several categories Stroustrup/Programming 51
Write embedded if/else statements Exercise Leap year testing logic Stroustrup/Programming 52
if (richter>=8. 0) cout <<“most structure falln”; else { if (richter>=7. 0) cout <<“Many buildings destroyedn”; else { if (richter >=6. 0) cout <<“Many building consi…n”; else { if (richter>=4. 5) { cout <<“damage to. . n”; } else cout <<“No des…n”; } } Stroustrup/Programming 53
if (richter>=8. 0) cout <<“most structure falln”; else if (richter>=7. 0) { cout <<“Many buildings destroye if (richter>=7. 0) else cout <<“Many buildings destroyedn”; if (richter >=6. 0) else { cout <<“Many building consi… if (richter >=6. 0) else cout <<“Many building consi…n”; if (richter>=4. 5) else cout <<“damage to. . n”; { else if (richter>=4. 5) cout <<“No des…n”; { cout <<“damage to. . n”; } else cout <<“No des…n”; } } Stroustrup/Programming 54
if (richter >= 8. 0) if (richter>=8. 0) cout <<“most structure falln”; cout << "Most structures fall"; else if (richter >= 7. 0) if (richter>=7. 0) cout <<“Many buildings destroyedn”; cout << "Many buildings else destroyed"; if (richter >=6. 0) else if (richter >= 6. 0) cout <<“Many building consi…n”; cout << "Many buildings …"; else if (richter>=4. 5) else if (richter >= 4. 5) cout <<“damage to. . n”; cout << "Damage to …"; else cout <<“No des…n”; cout << "Generally no damage"; Stroustrup/Programming 55
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 >> num 1 >> op >> num 2; //test whether op is equal to ‘+’, ‘-’, ’*’, ’/’. Stroustrup/Programming 56
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 <<“Total is: “ << n 1*p 1+n 2*p 2 <<“n”; cout <<“total is: “ << double total <<“n”; //not an expression Stroustrup/Programming 57
The world’s first “real program” running on a storedprogram 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 58
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 59
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 60
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 61
int main() { int square(int x) i=0; { while (i<100) { return x * x; } square(i) i<100 } } i==100 Stroustrup/Programming 62
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 63
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); int y = max(19, -27); int z = max(20, 20); Stroustrup/Programming // x becomes 9 // y becomes 19 // z becomes 20 64
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 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 65
Vector is the most useful standard library data type 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] 1 4 2 v’s elements: Stroustrup/Programming v[3] v[4] 3 5 66
vector<int> v; // start off empty v: 0 v. push_back(1); v: // add an element with the value 1 1 v. push_back(4); (“the back”) v: // add an element with the value 4 at end 2 v. push_back(3); (“the back”) v: 1 1 4 // add an element with the value 3 at end 3 Stroustrup/Programming v[0] 1 v[1] 4 v[2] 3 67
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 68
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 69
// “boilerplate” left out vector<string> words; string s; while (cin>>s && s != "quit") words. push_back(s); // && means AND 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 70
// Note that duplicate words were printed multiple times. For // example “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 71 Stroustrup/Programming
// 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>w 2; if (0<words. size()) { // Note style { } w 2. push_back(words[0]); for (int i=1; i<words. size(); ++i) if(words[i-1]!=words[i]) w 2. push_back(words[i]); } cout<< "found " << words. size()-w 2. size() << " duplicatesn"; for (int i=0; i<w 2. size(); ++i) cout << w 2[i] << "n"; Stroustrup/Programming 72
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 73
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 74
How to deal with errors Stroustrup/Programming 75
b4185c3c19d65798d3785ab672f161f1.ppt