Here are a few questions to help you clarify your understanding of advanced branching — switches and the ?: operator.
A ?: operation can typically replace an if structure when _____. (Hint: there may be more than one.)
Rewrite the following if structure as a ?: operation. (Hints: Nesting may be required... There should be only one cout statement when you are done.)
cout << "Your value is "; if (x > 0) { cout << "positive"; } else if (x < 0) { cout << "negative"; } else { cout << "zero"; } cout << ".\n";
cout << "Your value is " << (x > 0 ? "positive" : (x < 0 ? "negative" : "zero")) << ".\n";
What conditions are necessary for a branching structure (like a cascading if, for instance) to be replaced by a switch structure? (Hint: There are at least four...but there could be as many as seven!)
TRUE✗ | FALSE✓ | Only if structures can be nested: ?: and switches are too complicated. | ||
---|---|---|---|---|
TRUE✗ | FALSE✓ | You can't mix different structures when nesting: an if inside a switch or a switch inside an if. | ||
TRUE✗ | FALSE✓ | And, whatever you do, never try to nest a loop inside a branch or vice-versa! That is just WAY too confusing! |
Write a switch structure to print the average score of the grade-range when you are given the user's letter grade. (i.e. If they enter 'A', you'd print 95, etc.)
switch (grade) { case 'A': score = 95; break; case 'B': score = 85; break; case 'C': score = 75; break; case 'D': score = 65; break; case 'F': score = 30; break; default: score = -1; break; }
Write a switch structure to calculate the number of days since the last Dec 31st. The current month, day of the month, and year are in those respective variables. Store the calculated number of days in that (<--) variable.
days = day; switch (month-1) { case 11: days += 30; case 10: days += 31; case 9: days += 30; case 8: days += 31; case 7: days += 31; case 6: days += 30; case 5: days += 31; case 4: days += 30; case 3: days += 31; case 2: days += 28; case 1: days += 31; } if ( month > 2 && year % 4 == 0 && (year % 100 != 0 ¦¦ year % 400 == 0)) { days++; }