Tom Kelliher, CS17
Mar. 11, 1996
We now begin to add decision making capabilities to our programs.
Consider the tax computation program:
How about:
federalTax = FEDERAL_BASE + (grossIncome - FEDERAL_EXEMPTION) * FEDERAL_RATE;
Or:
if (grossIncome <= FEDERAL_EXEMPTION) federalTax = FEDERAL_BASE; else federalTax = FEDERAL_BASE + (grossIncome - FEDERAL_EXEMPTION) * FEDERAL_RATE;What was the root of the problem with the first fragment?
C++'s selection statements:
Form:
if (<Expression>) <ExpressionTrueStatement>; else <ExpressionFalseStatement>;
{ ... }
.
{ ... }
.
Easily confused with =:
int i = 3; if (i == 3) cout << "i is 3.\n"; else cout << "i isn't 3.\n"; i = 6; if (i = 3) cout << "i is 3.\n"; else cout << "i isn't 3.\n";
int i = 3; if (i != 3) cout << "i isn't 3.\n"; else cout << "i is 3.\n";Same effect as == if?
Examples:
int i = 4, j = 4, k = 5, l; l = i == j; l = i > k; cout << (l < j) << endl; // parentheses required --- see next section i = 4; j = 10; k = 6; l = i < j < k; // left associative
Consider deciding if a number is divisible by 10:
if (n % 10 == 0) cout << "Divisible by 10.\n"; else cout << "Not divisible by 10.\n";Simplified:
if (n % 10) cout << "Not divisible by 10.\n"; else cout << "Divisible by 10.\n";Same effect.
Simpler?
Easier to read?
<<
, >>
(left)
if (filingStatus == 1) cout << "Single"; else if (filingStatus == 2) cout << "Married filing jointly"; else if (filingStatus == 3) cout << "Married filing separately"; else if (filingStatus == 4) cout << "Head of household"; else cout << "Error in filing status;";Exactly one cout taken.
Easier to read:
if (filingStatus == 1) cout << "Single"; else if (filingStatus == 2) cout << "Married filing jointly"; else if (filingStatus == 3) cout << "Married filing separately"; else if (filingStatus == 4) cout << "Head of household"; else cout << "Error in filing status;";
if (creditStanding > 6) { if (balance <= 20.0) minPayment = balance; else if (balance <= 100) minPayment = 10.0 else minPayment = 0.1 * balance; } else minPayment = balance;Compound block necessary due to structure of problem.
Chapter 5 Study Guide Programming Exercises 1, 2, 3, 5, 9.