Control, Functions, Classes ● We’ve used built-in types like int and double as well as the standard class string and the streams cin and cout ➤ Each type supports certain operations and has a specific range of values • What are these for the types we’ve seen so far? ➤ We need more than these basic building blocks, why? ● We’ve used void functions to encapsulate concepts/statements with one name, avoid repeated code, help develop programs ➤ Functions with parameters are useful ➤ We need functions that return values to solve more problems than we’re currently able to solve 4.1 A Computer Science Tapestry
Types of control ● Selection: choose from among many options according to criteria the programmer codes (from which the user chooses) ➤ If response is yes do this, else do that ➤ If year is a leap year number of days is 366, else 365 ➤ If PIN is incorrect three times, keep banking card ➤ If 10 th caller, we have a winner ● Repetition (next chapter), repeatedly execute statements until criteria met ➤ Print twelve months of a calendar ➤ Allow three attempts at PIN entry ➤ Make moves in game until game is over 4.2 A Computer Science Tapestry
Problem solving leads to programming ● Which is the better value, a 10 inch, $10.95 pizza or a 12 inch $15.95 pizza? ➤ Details needed to solve the problem (no computer)? ➤ What’s missing from programming repertoire? ➤ Print two price/sq. in values, let user make conclusions ➤ Program should determine best value after calculating ● We need selection (why?) and we’d like a function to return a value for comparison (what’s the function?) if ( PizzaValue(10,10.95) > PizzaValue(12,15.95) ) cout << "10 inch pizza is better value" << endl; 4.3 A Computer Science Tapestry
First step, the assignment operator ● Avoid repeated calculations void SpherePizza(double radius, double price) { double volume; volume = 4.0/3*radius*radius*radius*3.1415; double area; area = 4*radius*radius*3.1415; cout << " area = " << area << endl; cout << " volume = " << volume << endl; cout << " $/cu.in " << price/volume << endl; } ● Assign a value to a variable to give it a value ➤ We have used input stream to enter values for variables ➤ Read the assignment operator as gets , “area gets …” • Avoids confusion with equality operator we’ll see later 4.4 A Computer Science Tapestry
Calculating change (see change.cpp ) int main() { int amount; int quarters, dimes, nickels, pennies; cout << "make change in coins for what amount: "; cin >> amount; quarters = amount/25; amount = amount - quarters*25; dimes = amount/10; amount = amount - dimes*10; // more code here, see the full program } ● How does amount = amount - dimes*10 execute? ➤ Evaluate expression on right hand side of operator = ➤ Store value in variable named on left hand side ➤ Problem if same variable used on both sides? Why? • Differences between reading and writing values 4.5 A Computer Science Tapestry
Problems with code in change.cpp ? // previous code for entering value, calculating #quarters dimes = amount/10; amount = amount - dimes*10; nickels = amount/5; amount = amount - nickels*5; pennies = amount; cout << "# quarters =\t" << quarters << endl; cout << "# dimes =\t" << dimes << endl; cout << "# nickels =\t" << nickels << endl; cout << "# pennies =\t" << pennies << endl; ● What about output statement if there are no quarters? ● What about repeated code? ➤ Code maintenance is sometimes more important than code development. Repeated code can cause problems, why? 4.6 A Computer Science Tapestry
Control via selection, the if statement void Output(string coin, int amount) { if (amount > 0) { cout << "# " << coin << " =\t" << amount << endl; } } int main() { // code for providing values to variables, now output Output("quarters",quarters); Output("dimes",dimes); Output("nickels",nickels); Output("pennies",pennies); } ● User enters 23 cents, what’s printed? Why? ➤ Selection statement determines if code executes; test or guard expression evaluates to true or false ➤ true/false are boolean values 4.7 A Computer Science Tapestry
Selection using if/else statement int main() { string name; cout << "enter name: "; cin >> name; if (name == "Ethan") { cout << "that’s a very nice name" << endl; } else { cout << name << " might be a nice name" << endl; } return 0; } ● What if user enters “ethan” ? or “ Ethan” ● How many statements can be guarded by if or else? ● What other tests/guards can be used (we’ve seen < and == ) 4.8 A Computer Science Tapestry
More Operators: Relational ● The guard/test in an if statement must be a Boolean expression (named for George Boole) ➤ Values are true and false ➤ bool is a built-in type like int , double , but some older compilers don’t support it int degrees; bool isHot = false; cout << "enter temperature: "; cin >> degrees; if (degrees > 95) { isHot = true; } // more code here ● Relational operators are used in expressions to compare values: <, <=, >, >=, ==, !=, used for many types ➤ See Table 4.2 and A.4 for details, precedence, etc. 4.9 A Computer Science Tapestry
Details of Relational Operators ● Relational (comparison) operators work as expected with int and double values, what about string and bool ? 23 < 45 49.0 >= 7*7 "apple" < "berry" ● Strings are compared lexicographically (alphabetically) so that "ant" < "zebra" but (suprisingly?) "Ant" < "zebra" ➤ How do lengths of strings compare? ➤ Why does uppercase ‘A’ come before lowercase ‘z’? ● Boolean values have numeric equivalents, 1 is true, 0 is false cout << (23 < 45) << endl; cout << ("guava" == "Guava") << endl; 4.10 A Computer Science Tapestry
Relational Operators: details, details,… ● Use parentheses liberally, or hard-to-find problems occur cout << 23 + 4 < 16 - 2 << endl; ➤ Causes following error using g++, fix using parentheses rather than deciphering: invalid operands ‘int’ and ‘ostream & ()(ostream &)’ to binary ‘operator <<’ ● What about true/false and numeric one/zero equivalent? if (3 + 4 – 7) { cout << "hi" << endl; } else { cout << "goodbye" << endl; } 4.11 A Computer Science Tapestry
Logical operators ● Boolean expressions can be combined using logical operators: AND, OR, NOT ➤ C++ equivalents are && , || , and ! , respectively • (standard requires and , or , not , most compilers don’t) if (90 <= grade) { if (grade < 95) { cout << "that’s an A" << endl; } } ➤ What range of values generates ‘A’ message? Problems? if (90 < grade && grade < 95) { cout << "that’s an A" << endl; } 4.12 A Computer Science Tapestry
Short-circuit Evaluation ● Subexpressions in Boolean expressions are not evaluated if the entire expression’s value is already known if (count != 0 && scores/count < 60) { cout << "low average warning" << endl; } ➤ Potential problems if there are no grades to average? What happens in this case? ➤ Alternatives in absence of short-circuit evaluation: if (count != 0) { if (scores/count < 60) { cout << "low average warning" << endl; } } ➤ Examples when OR short-circuits? 4.13 A Computer Science Tapestry
Donald Knuth (b. 1938) Scholar, practitioner, artisan ● ➤ Has written three of seven+ volumes of The Art of Computer Programming ➤ Began effort in 1962 to survey entire field, still going Strives to write beautiful programs ● ➤ Developed TeX to help typeset his books, widely used scientific document processing program Many, many publications ● ➤ First was in Mad Magazine ➤ On the Complexity of Songs ➤ Surreal Numbers 4.14 A Computer Science Tapestry
It’s all relative and it depends I make the best bread in the universe I make the best bread in the city I make the best bread in the world I make the best bread on the block 4.15 A Computer Science Tapestry
Richard Stallman (born 1953) Described by some as “world’s best ● programmer” ➤ Wrote/developed GNU software tools, particularly g++ ➤ Believes all software should be free, but like “free speech”, not “free beer” ➤ Won MacArthur award for his efforts and contributions ➤ League for Programming Freedom Gnu/Linux is a free operating ● • Local tie-in: Red Hat Linux, system and computing •headquarted in Durham, NC environment •IPO in 1999 at $14 ➤ Heavy industry/web use •One month later at $110+ ➤ Wintel killer?? •Markets “free” product 4.16 A Computer Science Tapestry
Recommend
More recommend