Tutorial 9
More on the Selection Structure
In Tutorial 8 the selection structure was introduced and implemented using the if and if/else forms of the structure. This tutorial continues discussing the selection structure by introducing and implementing the third form of the selection structure, which is the switch form. The concept of nesting selection structures is also discussed and implemented.
After completing the tutorial, the student will be able to:
Lecture Notes
Review the selection structure and design methods
The selection structure, also called the decision structure, is one of the three basic control structures used in programming. The other two are sequence, which has been covered previously, and the repetition structure, which will be covered in a later tutorial. The selection structure is used when you would like the program to make a decision, or comparison. Then, dependent upon the outcome of the decision, one of two paths will be chosen (the true path or the false path). Note that the decision within the selection structure will also result in either true or false, which is called a boolean result.
While the concept of a selection structure is quite simple, it is important to properly design the selection structure. Both flowcharts and pseudocode have been covered previously (review if necessary), however new flowchart symbols will be now be introduced. The diamond symbol represents a decision and is called the selection/repetition symbol. Each diamond has one flowline entering the symbol, and two flowlines leaving the symbol. The two flowlines leaving the symbol represent the true and false paths and should be marked accordingly. See page 268 for an example of a flowchart containing a selection structure.
Even though flowcharts are commonly used in representing selection structures, many programmers still wish to use pseudocode. You should always use whichever design method is most effective for you. Many programmers will use a combination of flowcharts and pseudocode. Different programming structures may lend themselves to being designed in either a flowchart or pseudocode. See page 267 for an example of a selection structure in pseudocode.
Note: Now that the switch form of the selection structure is being introduced, the design process utilizing pseudocode and/or flowcharts, while similar, will look different from a standard if/else form of the structure. The same flowchart symbol is used to represent the condition (diamond), however instead of one flowline coming out of the structure for the true path, many flowlines may now be coming out of the structure. See Figure 9-16 on page 314 for an example.
Nesting a selection structure
You can nest a selection structure within either the true path or false path of another selection structure. You would use a nested selection structure if more than one decision needs to be made before the appropriate action can be taken. The outer selection structure always represents the primary decision, while the nested (or inner) selection structure always represents the secondary decision.
While nesting a selection structure seems to be fairly straight forward, one must properly design the nested structure if they wish to be successful in implementing their desired logic. Also, it is imperative to properly code the structure. Following the proper indentation rules, as well as making the code readable, is a must in order for the code to execute successfully. Please review the example on page 301. The problem is presented in pseudocode and flowchart form, as well as implementing the actual C++ code. Another example of just C++ code is presented on pages 304-305. Both of these examples are very good ones to define your own rules for coding nested selection structures.
Recognizing common logic errors
Typically, logic errors commonly made when writing selection structures are a result of one of the following mistakes:
In Figure 9-8 on page 308 you will find two algorithms. The first algorithm properly solves the problem, while the second algorithm improperly solves the problem. While it may appear that the second algorithm properly solves the problem (it would display "3-week vacation" as would the first if the status were F and the years were greater than 5), there is still a problem due to the way it is coded. The second algorithm will display "2-week vacation" if the status is not F and/or the number of years is less than or equal to 5. The first algorithm will only display "2-week vacation" if the status if F and the number of years is less than or equal to 5. As you can see, a logical operator (second algorithm) cannot simply be substituted for a nested structure (first algorithm).
Another common error made when writing a selection structure that contains a nested selection structure is to reverse the primary and secondary decisions. Figure 9-10 on page 309 shows an example of this type of error. Unlike the selection structures in the correct algorithm, which determine the employment status before determining the number of years employed, the selection structures in the incorrect algorithm determine the number of years employed before determining the employment status. By reversing these two decisions, the problem is completely changed.
The third common error made when writing selection structures is to include an unnecessary nested selection structure. In most cases, a selection structure containing this error still will produce the correct results, however it does so less efficiently than selection structures properly designed. Figure 9-12 on page 311 shows this type of error. Unlike the correct algorithm, which contains two selection structures, the inefficient algorithm contains three selection structures. Follow the code and produce the same desk-check table as in Figure 9-13. You will see while the correct result is obtained, it is obtained is a less efficient manner.
Multiple-path selection using if/else
Some algorithms require selection structures that are capable of choosing from several alternatives. You can create such selection structures, commonly referred to as multiple-path structures, using either the if/else or switch form of the selection structure. Review the two sets of code in Figure 9-15 on page 313. Although you can write the if/else selection structure using either of the two methods, the second version provides a much more convenient way of writing this logic, and is more readable. The next section discusses the switch form of selection structures, which is the other way of creating a multiple-path structure.
Coding the switch selection structure
Remember from tutorial 8 that most programming languages offer three forms of the selection structure: if, if/else, and switch (also referred to as case). Since tutorial 8 covered the if and if/else forms of the selection structure, the switch form of the selection structure will be covered in this tutorial. While the same logic may be represented using the if/else or nested if/else form of the selection structure, it is often simpler and clearer (remember readability) to use the switch form, especially in situations in which the selection structure has many paths from which to choose. The syntax of the C++ switch statement is listed below:
switch (selectorExpression)
{
case value1: one or more statements
LEFTSQUAREcase value2: one or more statementsRIGHTSQUARE
LEFTSQUAREcase valueN: one or more statementsRIGHTSQUARE
LEFTSQUAREdefault: one or more statements processed when the selectorExpression does not match any of the valuesRIGHTSQUARE
}//end switch
You will notice above that the switch clause is composed of the keyword switch followed by a selectorExpression enclose in parentheses. The selectorExpression can contain any combination of variables, constants, functions, and operators, as long as the combination results in a value whose data type is either bool, char, short, int, or long.
Between the switch statement’s opening and closing braces are the individual case clauses, each representing a different path that the selection structure can follow. You may have as many case clauses as necessary in a switch statement. If the switch statement includes a default clause, it is usually the last clause in the statement just before the ending brace.
Each of the individual clauses within the switch statement (except for the default clause) contains a value, followed by a colon. The data type of the value should be compatible with the data type of the selectorExpression. (This is similar to an if statement when a variable is being compared to a single data value). Following the colon in each case clause are one or more statements that will be processed when the selectorExpression matches that case’s value. Notice that the statement(s) within the case clause are not entered as a statement block (are not enclosed in braces).
Once a match has been made between the selectorExpression and a case’s value, and the statement(s) that you wish to have processed have been executed, you would like the computer to advance to the next statement after the switch statement. To enable the computer to do this, you must code the break statement after the statement(s) you wish to process for each case clause. The break statement tells the computer to break out of the switch statement at this point, and proceed to the next statement following the switch statement. Note that any remaining case clauses will not be checked, which would not be necessary anyway since we have a match.
Note that the last optional clause in the switch statement is the default clause. The statement(s) in the default clause are executed if no matches occur between the selectorExpression and a case’s value. (This is similar to the else clause in an if/else statement). Notice that there is not a break coded after the statement(s) in a default clause. This is because the default clause is the last thing coded in the switch statement.
Just like the if and if/else statements, the switch statement should end with a comment after the ending brace. Remember that this is good programming practice that will help with readability and modifiability.
Discussion Topics/Additional Activities
Solutions to Concept Lesson Exercises
cout << "Equal" << endl;
else if (quantity > 10)
cout << "Over 10" << endl;
else cout << "Not over 10" << endl;
//end ifs
cin >> code;
cout << "Enter the sales: ";
cin >> sales;
if (code == 1 || code == 2)
cout << sales * .12 << endl;
else if (code == 3)
cout << sales * .15 << endl;
else if (code == 4)
cout << sales * .20 << endl;
else cout << "Error" << endl;
//end ifs
cin >> code;
cout << "Enter the sales: ";
cin >> sales;
switch (code)
{
case 1: cout << sales * .02 << endl;
break;
case 2:
case 3:
case 4: cout << sales * .05 << endl;
break;
case 5: cout << sales * .1 << endl;
break;
case 6:
case 7: cout << sales * .15 << endl;
break;
default: cout << "Error" << endl;
} //end switch
4.
//T9ConE04.cpp - displays a message based on the number entered by the user #include <iostream> using namespace std; int main() { //declare variable int animal = 0; //enter input cout << "Enter a number: "; cin >> animal; //display output if (animal == 1) cout << "Dog" << endl; else if (animal == 2) cout << "Cat" << endl; else cout << "Bird" << endl; //end ifs return 0; } //end of main function |
5.
//T9ConE05.cpp - displays the month corresponding to the number entered by the user #include <iostream> using namespace std; int main() { //declare variable int month = 0; //enter input cout << "Enter the month number: "; cin >> month; //display output switch (month) { case 1: cout << "January" << endl; break; case 2: cout << "February" << endl; break; case 3: cout << "March" << endl; break; case 4: cout << "April" << endl; break; case 5: cout << "May" << endl; break; case 6: cout << "June" << endl; break; case 7: cout << "July" << endl; break; case 8: cout << "August" << endl; break; case 9: cout << "September" << endl; break; case 10: cout << "October" << endl; break; case 11: cout << "November" << endl; break; case 12: cout << "December" << endl; break; default: cout << "Error" << endl; } //end switch return 0; } //end of main function |
6.
//T9ConE06.cpp - displays a bonus amount #include <iostream> using namespace std; int main() { //declare variables int sales = 0; int bonus = 0; //enter input cout << "Enter the sales amount: "; cin >> sales; //assign bonus if (sales >= 100 && sales <= 250) bonus = 25; else if (sales > 250) bonus = 50; else bonus = 0; //end ifs //display output cout << "Bonus: " << bonus << endl; return 0; } //end of main function |
7.
//T9ConE07.cpp - displays a seminar fee #include <iostream> using namespace std; int main() { //declare variables char memberStatus = ' '; int age = 0; int fee = 0; //enter status cout << "Membership status (M for member and N for non-member): "; cin >> memberStatus;
//assign seminar fee if (memberStatus == 'M' || memberStatus == 'm') { cout << "Age: "; cin >> age; if (age < 65) fee = 10; else fee = 5; } else fee = 20; //end ifs
//display output cout << "Fee: " << fee << endl; return 0; } //end of main function |
8.
//T9ConE08.cpp - displays a grade #include <iostream> using namespace std; int main() { //declare variables int score1 = 0; int score2 = 0; int score3 = 0; float avg = 0.0; char grade = ' ';
//enter scores cout << "Score 1: "; cin >> score1; cout << "Score 2: "; cin >> score2; cout << "Score 3: "; cin >> score3; //calculate average avg = (score1 + score2 + score3) / 3.0; //assign grade if (avg >= 90.0) grade = 'A'; else if (avg >= 80.0) grade = 'B'; else if (avg >= 70.0) grade = 'C'; else if (avg >= 60.0) grade = 'D'; else grade = 'F'; //end ifs
//display output cout << "Grade: " << grade << endl; return 0; } //end of main function |
9.
//T9ConE09.cpp - displays class rank #include <iostream> using namespace std; int main() { //declare variable int code = 0; //enter input cout << "Enter the code: "; cin >> code; //display output switch (code) { case 1: cout << "Freshman" << endl; break; case 2: cout << "Sophomore" << endl; break; case 3: cout << "Junior" << endl; break; case 4: cout << "Senior" << endl; break; default: cout << "Error" << endl; } //end switch return 0; } //end of main function |
10. b. Below Average
c. The switch statement does not display anything on the screen.
d. Below Average
Incomplete
11.
//T9ConE11.cpp - displays a message based on the day number entered by the user #include <iostream> using namespace std; int main() { //declare variable int day = 0; //enter input cout << "Enter the day (1 through 12): "; cin >> day; //display output
switch (day) { case 1: cout << "1 partridge in a pear tree" << endl; break; case 2: cout << "2 turtle doves" << endl; break; case 3: cout << "3 french hens" << endl; break; case 4: cout << "4 calling birds" << endl; break; case 5: cout << "5 golden rings" << endl; break; case 6: cout << "6 geese a laying" << endl; break; case 7: cout << "7 swans a swimming" << endl; break; case 8: cout << "8 maids a milking" << endl; break; case 9: cout << "9 ladies dancing" << endl; break; case 10: cout << "10 lords a leaping" << endl; break; case 11: cout << "11 pipers piping" << endl; break; case 12: cout << "12 drummers drumming" << endl; break; default: cout << "Error in day number." << endl; } //end switch
return 0; } //end of main function
|
12.
//T9ConE12.cpp - displays the price of an order #include <iostream> using namespace std; int main() { //declare variables int status = 0; int units = 0;
//enter input cout << "Customer status (1 for wholesaler, 2 for retailer): "; cin >> status; cout << "Number of units ordered: "; cin >> units;
//calculate and display order price switch (status) { case 1: if (units >= 1 && units <= 4) cout << "Total $" << units * 10 << endl; else if (units >= 5) cout << "Total $" << units * 9 << endl; else cout << "Invalid number of units." << endl; break; case 2: if (units >= 1 && units <= 3) cout << "Total $" << units * 15 << endl; else if (units >= 4 && units <= 8) cout << "Total $" << units * 14 << endl; else if (units >= 9) cout << "Total $" << units * 12 << endl; else cout << "Invalid number of units." << endl; break; default: cout << "Invalid status." << endl; } //end switch return 0; } //end of main function |
13. Changes made to the original code are shaded.
/T9ConE13.cpp - displays the state //corresponding to the code entered by the user #include <iostream> using namespace std; int main() { //declare variable int stateCode = 0; //enter input item cout << "Enter a number from 1 to 5: "; cin >> stateCode; //display output switch (stateCode) { case 1: cout << "Illinois" << endl; break; case 2: cout << "Kentucky" << endl; break; case 3: cout << "New Hampshire" << endl; break; case 4: cout << "Vermont" << endl; break; case 5: cout << "Massachusetts" << endl; break; default: cout << "Unknown state" << endl; } //end switch return 0; } //end of main function |
Solutions to Application Lesson Exercises
1.
//T9AppE01.cpp - displays the commission #include <iostream> using namespace std; //function prototype float calcCommission(int); int main() { int sales = 0; float commission = 0.0;
//enter input data cout << "Enter sales: "; cin >> sales; if (sales > 0) { //calculate and display commission commission = calcCommission(sales); cout << "Commission: " << commission << endl; } else cout << "No commission calculated" << endl; //end if return 0; } //end of main function //*****program-defined functions***** float calcCommission(int amountSold) { //calculates and returns the commission float commDollars = 0.0; if (amountSold <= 100000) commDollars = amountSold * .02; else if (amountSold <= 200000) commDollars = amountSold * .04; else if (amountSold <= 300000) commDollars = amountSold * .06; else if (amountSold <= 400000) commDollars = amountSold * .08; else commDollars = amountSold * .1; //end ifs return commDollars; } //end of calcCommission function |
2.
IPO charts:
main function
Input |
Processing |
Output |
number of registrants
|
Processing items: none Algorithm:
total owed = calcTotalOwed(number of registrants) display the total owed else display "Incorrect number" message |
total owed |
calcTotalOwed function
Input |
Processing |
Output |
number of registrants
|
Processing items: fee per person Algorithm:
assign 100 as the fee per person else if (the number of registrants <= 10) assign 80 as the fee per person else assign 60 as the fee per person |
total owed |
Desk-check tables:
main function
registrants |
totalOwed |
0 4 0 8 0 12 0 0 0 -2 |
0 400 0 640 0 720 0 0 |
calcTotalOwed function
people |
feePerPerson |
total |
4 8 12 |
0 100 0 80 0 60 |
0 400 0 640 0 720 |
//T9AppE02.cpp - displays the total owed #include <iostream> using namespace std; //function prototype int calcTotalOwed(int); int main() { int registrants = 0; int totalOwed = 0;
//enter input data cout << "Enter number of registrants: "; cin >> registrants; if (registrants > 0) { //calculate and display total owed totalOwed = calcTotalOwed(registrants); cout << "Total owed: " << totalOwed << endl; } else cout << "Incorrect number" << endl; //end if return 0; } //end of main function //*****program-defined functions***** int calcTotalOwed(int people) { //calculates and returns the total owed int feePerPerson = 0; int total = 0; if (people <= 4) feePerPerson = 100; else if (people <= 10) feePerPerson = 80; else feePerPerson = 60; //end ifs total = people * feePerPerson; return total; } //end of calcTotalOwed function |
3.
IPO Chart:
Input |
Processing |
Output |
state code
|
Processing items: none Algorithm:
1 display 25 2, 5, 6 display 30 3, 4 display 40 Other display "Incorrect state code" |
shipping charge |
Desk-check table:
stateCode |
0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 -2 |
//T9AppE03.cpp - displays a shipping charge #include <iostream> using namespace std; int main() { int stateCode = 0;
//enter input data cout << "Enter the state code: "; cin >> stateCode; //display shipping charge switch (stateCode) { case 1: cout << "Shipping charge is $25" << endl; break; case 2: case 5: case 6: cout << "Shipping charge is $30" << endl; break; case 3: case 4: cout << "Shipping charge is $40" << endl; break; default: cout << "Incorrect state code" << endl; } //end switch
return 0; } //end of main function |
4.
IPO Chart:
Input |
Processing |
Output |
seat location |
Processing items: none Algorithm:
display 75 as the price else if (the seat location is P or p) display 30 as the price else if (the seat location is L or l) display 21 as the price else display an error message end ifs |
price |
Desk-check table:
location |
B p L g |
//T9AppE04.cpp - displays the price of a concert ticket #include <iostream> using namespace std; int main() { char location = ' ';
//enter input data cout << "Enter the seat location: "; cin >> location; //display ticket price if (location == 'B' || location == 'b') cout << "Ticket price: $75" << endl; else if (location == 'P' || location == 'p') cout << "Ticket price: $30" << endl; else if (location == 'L' || location == 'l') cout << "Ticket price: $21" << endl; else cout << "Invalid location" << endl; //end ifs
return 0; } //end of main function |
5.
IPO Chart:
Input |
Processing |
Output |
years employed |
Processing items: none Algorithm:
display 0 as the vacation weeks else if (the years employed is less than or equal to 5) display 1 as the vacation weeks else if (the years employed is less than or equal to 10) display 2 as the vacation weeks else if (the years employed is greater than 10) display 3 as the vacation weeks else display "Invalid years" message end ifs |
vacation weeks |
Desk-check table:
years |
0 0 0 2 0 10 0 11 0 -2 |
//T9AppE05.cpp - displays the number of vacation weeks due an employee #include <iostream> using namespace std; int main() { int years = 0;
//enter input data cout << "Enter the years employed: "; cin >> years; //display vacation weeks if (years == 0) cout << "Vacation weeks: 0" << endl; else if (years > 0 && years <= 5) cout << "Vacation weeks: 1" << endl; else if (years > 5 && years <= 10) cout << "Vacation weeks: 2" << endl; else if (years > 10) cout << "Vacation weeks: 3" << endl; else cout << "Invalid years" << endl; //end ifs
return 0; } //end of main function |
6.
//T9AppE06.cpp - displays fat calories and fat percentage #include <iostream> using namespace std; //function prototype void calcFatInfo(int, int, int &, float &); int main() { int totalCal = 0; int fatGrams = 0; int fatCal = 0; float fatPercent = 0.0; //enter input data cout << "Total calories: "; cin >> totalCal; cout << "Grams of fat: "; cin >> fatGrams; //validate input data if (totalCal >= 0 && fatGrams >= 0) { //valid data calcFatInfo(totalCal, fatGrams, fatCal, fatPercent); cout << fixed; cout.precision(0); cout << "Fat calories: " << fatCal << endl; cout << "Fat percentage: " << fatPercent << "%" << endl; if (fatPercent <= 30) cout << "Low-fat food" << endl; else cout << "High-fat food" << endl; //end if } else //invalid data cout << "Input error" << endl; //end if return 0; } //end of main function //*****program-defined functions***** void calcFatInfo(int tCal, int grams, int &fCal, float &fPer) { //calculate fat calories and fat percentage fCal = grams * 9; fPer = float(fCal) / float(tCal) * 100; } //end of calcFatInfo function |
7.
IPO charts:
main function
Input |
Processing |
Output |
gender activity level current weight
|
Processing items: data OK Algorithm:
calculate daily calories = calcDailyInfo(gender, activity level, current weight) display daily calories else display error message |
daily calories |
getInputData function
Input |
Processing |
Output |
address of gender address of activity level address of current weight
|
Processing items: none Algorithm:
get activity level if (activity level is A or a or I or I) get current weight assign Y to valid |
gender activity level current weight valid (N) |
calcDailyInfo function
Input |
Processing |
Output |
gender activity level current weight
|
Processing items: none Algorithm:
if (activity level is A or a) daily calories = current weight * 12 else daily calories = current weight * 10 else if (activity level is A or a) daily calories = current weight * 15 else daily calories = current weight * 13 |
daily calories |
Desk-check tables:
gender (main) sex (getInputData) |
activityLevel (main) level (getInputData) |
currentWeight (main) pounds (getInputData) |
F F M M G F |
I A I A B |
0 150 0 120 0 180 0 200 0 0 |
main function only getInputData function only
dataOK |
dailyCalories |
|
validData |
Y Y Y Y N N |
0 1500 0 1440 0 2340 0 3000 0 0 |
|
N Y N Y N Y N Y N N |
calcDailyInfo function only
femaleMale |
activity |
curWeight |
maintainCals |
F F M M |
I A I A |
150 120 180 200 |
0 1500 0 1440 0 2340 0 3000 |
//T9AppE07.cpp - displays the number of daily calories needed to maintain current weight #include <iostream> using namespace std; //function prototypes char getInputData(char &, char &, int &); int calcDailyInfo(char, char, int); int main() { char gender = ' '; char activityLevel = ' '; int currentWeight = 0; char dataOk = ' '; int dailyCalories = 0;
//enter input data dataOk = getInputData(gender, activityLevel, currentWeight); if (dataOk == 'Y') { //calculate calories dailyCalories = calcDailyInfo(gender, activityLevel, currentWeight); cout << "Daily calories " << dailyCalories << endl; } else cout << "Incorrect input data entered" << endl; //end if return 0; } //end of main function //*****program-defined functions***** char getInputData(char &sex, char &level, int £s) { char validData = 'N'; cout << "Gender (F for female or M for male): "; cin >> sex; if (sex == 'F' || sex == 'f' || sex == 'M' || sex == 'm') { cout << "Activity level (A for active or I for inactive): "; cin >> level; if (level == 'A' || level == 'a' || level == 'I' || level == 'i') { cout << "Current weight: "; cin >> pounds; validData = 'Y'; } //end if } //endif return validData; } //end of getInputData function
int calcDailyInfo(char femaleMale, char activity, int curWeight) { int maintainCals = 0; if (femaleMale == 'F' || femaleMale == 'f') { if (activity == 'A' || activity == 'a') maintainCals = curWeight * 12; else maintainCals = curWeight * 10; //end if } else //male { if (activity == 'A' || activity == 'a') maintainCals = curWeight * 15; else maintainCals = curWeight * 13; //end if }//end if return maintainCals; } //end of calcDailyInfo function |
8.
IPO Chart:
Input |
Processing |
Output |
score 1 score 2
|
Processing items: average Algorithm:
display error message else get score 2 if (score 2 is less than 0) display error message else calculate the average by adding together score 1 and score 2, and then dividing the sum by 2 if (the average is greater than or equal to 70) display "Pass" message else display "Fail" message |
message (Pass or Fail) |
Desk-check table:
test1 |
test2 |
avg |
0.0 95.0 0.0 65.0 0.0 0.0 0.0 80.0 0.0 -1.0 |
0.0 73.0 0.0 50.0 0.0 100.0 0.0 -3.0 0.0 |
0.0 84.0 0.0 57.5 0.0 50.0 0.0 0.0 |
//T9AppE08.cpp - displays a message indicating //whether a student passed or failed a course #include <iostream> using namespace std; int main() { float test1 = 0.0; float test2 = 0.0; float avg = 0.0; //enter input data cout << "Enter first test score: "; cin >> test1; //display message if (test1 < 0) cout << "You entered a negative score for the first test." << endl; else { cout << "Enter second test score: "; cin >> test2; if (test2 < 0) cout << "You entered a negative score for the second test." << endl; else { avg = (test1 + test2) / 2; if (avg >= 70) cout << "Pass" << endl; else cout << "Fail" << endl; //end if } //end if } //end if
return 0; } //end of main function |
9.
IPO Chart:
Input |
Processing |
Output |
operation num 1 num 2
|
Processing items: temp Algorithm:
display error message else get num 1 get num2 if (operation is A or a) calculate sum by adding together num 1 and num 2 display sum else if (num 1 is less than num 2) assign num 1 to temp assign num 2 to num 1 assign temp to num 2 end if calculate the difference by subtracting num 2 from num 1 display the difference end if end if |
sum or difference |
Desk-check table:
operation |
num1 |
num2 |
sum |
diff |
temp |
A a S s G |
0 10 0 45 0 65 0 7 13 0 |
0 20 0 15 0 50 0 13 7 0 |
0 30 0 60 0 0 0 |
0 0 0 15 0 6 0 |
0 0 0 0 7 0 |
//T9AppE09.cpp - displays either the sum or difference #include <iostream> using namespace std; int main() { char operation = ' '; int num1 = 0; int num2 = 0; int sum = 0; int diff = 0; int temp = 0; //enter input data cout << "Enter operation (A or S): "; cin >> operation; //display message if (operation != 'A' && operation != 'a' && operation != 'S' && operation != 's') cout << "Incorrect operation" << endl; else { cout << "Enter first number: "; cin >> num1; cout << "Enter second number: "; cin >> num2; if (operation == 'A' || operation == 'a') { sum = num1 + num2; cout << "Sum: " << sum << endl; } else { if (num1 < num2) { temp = num1; num1 = num2; num2 = temp; } //end if diff = num1 - num2; cout << "Difference: " << diff << endl; } //end if } //end if return 0; } //end of main function |
10.
//T9AppE10.cpp - displays the commission #include <iostream> using namespace std; //function prototypes float calcCommission(int); char getAndValidateSales(int &); int main() { int sales = 0; float commission = 0.0; char validData = ' ';
//enter input data validData = getAndValidateSales(sales); if (validData == 'Y') { //calculate and display commission commission = calcCommission(sales); cout << "Commission: " << commission << endl; } else cout << "No commission calculated" << endl; //end if return 0; } //end of main function //*****program-defined functions***** char getAndValidateSales(int &dollars) { char valid = 'N'; cout << "Enter sales: "; cin >> dollars; if (dollars > 0) valid = 'Y'; return valid; } //end of getAndValidateSales function float calcCommission(int amountSold) { //calculates and returns the commission float commDollars = 0.0; if (amountSold <= 100000) commDollars = amountSold * .02; else if (amountSold <= 400000) commDollars = 2000 + .05 * (amountSold - 100000); else commDollars = 17000 + .1 * (amountSold - 400000); //end ifs return commDollars; } //end of calcCommission function |
11. Changes to the original code are shaded.
//T9AppE11.cpp - displays the salary amount //corresponding to the code entered by the user #include <iostream> using namespace std; int main() { //declare variable int code = 0; //get code from user cout << "Enter the code (1 through 5): "; cin >> code; //display salary
if (code == 1) cout << "$45,000" << endl; else if (code == 2 || code == 5) cout << "$33,000" << endl; else if (code == 3 || code == 4) cout << "$25,000" << endl; else cout << "Entry error" << endl;
//end ifs return 0; } //end of main function |