A.4. Chapter 6
A.4.1. Exercise 1 Solution
The decision can be made using a single if statement:
price = FULLPRICE;
if (age < 13 || age > 64)
{
price *= .5M;
}
The if statement checks for the child and senior price values and adjusts the price accordingly.
A.4.2. Exercise 2 Solution
The most important style consideration is consistency. The placement of curly braces is whatever you or your programming team decides works best for you. Personally, I think all if-else statement blocks should use curly braces, even when only a single statement is being controlled.
A.4.3. Exercise 3 Solution
It is appropriate to use cascading if statements anytime a single value can have multiple resolutions. Keep in mind that a switch might also be appropriate in lieu of a cascading if statement.
A.4.4. Exercise 4 Solution
if (x = y);
{
price =* .06;
}
There are a number of problems. First, the if expression uses the assignment operator rather than a test for equality. Second, the semicolon after the if expression and before the opening curly brace of the if statement block is an error. Third, the shortcut assignment-multiplication operator is backwards (it should be *=). Fourth, assuming that price is a decimal data type, which it probably should be, the .06 literal needs the M type designator after the literal.
A.4.5. Exercise 5 Solution
One possible solution is:
const int SMALL = 1; const int MEDIUM = 2; const int LARGE = 3; decimal smallPrice = 6.0M; decimal mediumPrice = smallPrice + 1.0M; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access