Make your own free website on Tripod.com

Tutorial 8

The Selection Structure

  The instructor’s notes for this tutorial will consist of the following:

 Overview

 Objectives

 Lecture Notes

 Discussion Topics/Additional Activities

 Solutions to Questions

 Solutions to Concept Lesson Exercises

 Solutions to Application Lesson Exercises

Overview

This tutorial covers one of the basic control structures used in programming which is the selection structure. Proper design of the selection structure is covered using both pseudocode and flowcharts. The syntax of both if and if/else are covered, which is the programming code that implements the selection structure in C++. Comparison and logical operators are introduced in order to represent conditions, while comparison of numeric, as well as character and string data, is covered.

Objectives

After completing the tutorial, the student will be able to:

 

Introduction to 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.

 

Coding the selection structure

Most programming languages offer three forms of the selection structure: if, if/else, and switch (also referred to as case). While this tutorial will cover only the if and if/else forms of the selection structure, the switch form of the selection structure will be covered in the next tutorial. The C++ if statement can be used to code both the if and if/else forms of the selection structure. The syntax of the C++ if statement is listed below:

if (condition)

one statement, or a block of statements enclosed in braces, to be processed when the condition is true

LEFTSQUAREelse

one statement, or a block of statements enclosed in braces, to be processed when the condition is falseRIGHTSQUARE

//end if

Note first that the else part of the if statement is optional. Dependent upon what logic you need to represent in your program, you may not need the else part of the if statement. Many situations may only require for an action to be performed if a condition is true. When using only the if statement without the else, if the condition were evaluated to be true, the statement(s) would be executed, and then control would be passed to the first statement after the //end if statement. If the condition were evaluated to be false, no statement(s) would be executed, and control would be passed to the first statement after the //end if statement.

While the //end if statement is not mandatory, it is very good programming practice. Since the if statement does not have a built-in statement that marks the end of the statement, by placing this comment at the end of the statement it makes the statement much more readable and easier to follow. This becomes invaluable when debugging the program.

In Figure 8-5 on page 270, different syntax is shown for the if statement dependent upon how many statements are to be processed under certain conditions. While this figure shows the proper syntax for different situations, the different syntax rules could be eliminated by simply placing braces around each set of statements to be executed. This holds true even if there would be only one statement to be executed. Therefore, each if/else statement would look similar to the last situation (multiple statements in true and false paths), while each if statement (no else) would look similar to the if form with multiple statements. Note while this may eliminate some coding rules for creating new code, the existing rules need to be understood for modifying existing code that another programmer may have written.

Comparison operators

As mentioned earlier the condition in the if or if/else statement is evaluated to be a boolean value (true or false). Therefore, we may say that the condition is a boolean expression, where each expression may consist of variables, constants, functions, arithmetic operators, comparison operators, and logical operators. One of the items that we have not covered from the permitted list above is a comparison operator.

A comparison operator, also known as a relational operator, is used to make comparisons in C++. Figure 8-6 on page 271 lists the C++ comparison operators along with their precedence. Note that just like mathematical operators had precedence numbers, so do comparison operators. Figure 8-7 on page 272 shows different examples of comparison operators.

Note that while many languages will use the equal sign (=) to be the "equal to" comparison operator, C++ cannot use the equal sign for this task. This is because the equal sign in C++ is reserved for being the assignment operator. Therefore C++ uses the double equal signs (==) to be the "equal to" comparison operator.

Logical operators

The only other part of a boolean expression that we have not covered is the logical operator. Logical operators are used to combine two or more conditions into one compound condition representing the boolean expression. The most commonly used logical operators are And and Or (Not is the other logical operator). When the And logical operator is used to create a compound condition, all of the conditions must be true for the compound condition to be true. On the other hand, when the Or logical operator is used, only one of the conditions needs to be true for the compound condition to be true. See the truth tables in figure 8-12 on page 276.

C++ uses special symbols to represent the And and Or logical operators in a program. The And operator in C++ is two ampersands (&&), and the Or operator is two pipe symbols (||). Note the location of the pipe symbol, which is on the same key as the backslash (\). Just like the relational operators, logical operators have a precedence number. In the case in which And (&&) and Or (||)are in the same condition, And (&&) will be evaluated before Or (||).

Overall order of precedence

Figure 8-13 on page 277 lists the order of precedence for arithmetic, comparison, and logical operators. Since a boolean expression may consist of any of the above, it is important to understand how the language will evaluate the statements that you write. Note that at any time two operators have the same priority in a condition, the leftmost operator will be evaluated first. This is similar to the rule for arithmetic operators that we previously covered, however now it applies to all operators used.

Comparisons of character and string data

While comparison of numeric data is fairly straight forward (even though you need to make sure of the data types you are comparing), comparison of character data may fool you. Remember that each character has its own unique ASCII value. Since each character is unique in its representation, comparisons of characters data must be case sensitive. Therefore, if you wish to test a value entered from a user for the letter ‘Y’, you must test to see if they entered a lower case ‘y’, or an upper case ‘Y’.

Note that discovery exercise #11 will show an example of the toupper function that will help in this comparison. The toupper function will also be covered in a later tutorial.

 

Solutions to Questions

1. a diamond 6. b false

2. c == 7. a true

3. a != 8. a true

4. c (item == "Chair" || item == "Desk") 9. a true

5. d (initial == ‘A’ || initial == ‘a’) 10. a arithmetic

 

Solutions to Concept Lesson Exercises

 

1. if (quantity > 10)

cout << "Over 10" << endl;

else

cout << "Not over 10" << endl;

//end if

 

2. cout << "Enter the hours: ";

cin << hours;

if (hours > 40)

cout << "Overtime" << endl;

else

cout << "Regular" << endl;

//end if

 

3.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

4.

//T8ConE04.cpp - displays a message based on the number entered by the user

#include <iostream>

using namespace std;

int main()

{

//declare variable

int units = 0;

//enter input

cout << "Enter the units: ";

cin >> units;

//display output

if (units < 0)

cout << "Entry error" << endl;

else

cout << "Valid number" << endl;

//end if

return 0;

} //end of main function

 

 5.

//T8ConE05.cpp - displays a message based on the number entered by the user

#include <iostream>

using namespace std;

int main()

{

//declare variable

int quantity = 0;

//enter input

cout << "Enter the quantity: ";

cin >> quantity;

//display output

if (quantity < 10)

cout << "Reorder" << endl;

else

cout << "OK" << endl;

//end if

return 0;

} //end of main function

 6.

//T8ConE06.cpp - displays a bonus amount

#include <iostream>

using namespace std;

int main()

{

//declare variables

float sales = 0.0;

float bonus = 0.0;

float rate = 0.0;

//enter input

cout << "Enter the sales: ";

cin >> sales;

//assign bonus

if (sales <= 250)

bonus = 10;

else

{

cout << "Enter the bonus rate: ";

cin >> rate;

bonus = rate * sales;

}

//end if

//display output

cout << "Bonus: " << bonus << endl;

return 0;

} //end of main function

 

7.

///T8ConE07.cpp - displays an employee's gross pay

#include <iostream>

using namespace std;

int main()

{

//declare variables

float hours = 0.0;

float rate = 0.0;

float gross = 0.0;

float overtime = 0.0;

//enter input

cout << "Enter the hours: ";

cin >> hours;

cout << "Enter the rate: ";

cin >> rate;

//calculate overtime pay and gross pay

if (hours <= 40)

gross = hours * rate;

else

{

overtime = (hours - 40) * rate * 1.5;

gross = 40 * rate + overtime;

}

//end if

//display output

cout << "Overtime pay: " << overtime << endl;

cout << "Gross pay: " << gross << endl;

return 0;

} //end of main function

 

8.

//T8ConE08.cpp - displays a message based on the character entered by the user

#include <iostream>

using namespace std;

int main()

{

//declare variables

char animal = ' ';

//enter input

cout << "Enter an ID: ";

cin >> animal;

//display output

if (animal == 'D' || animal == 'd')

cout << "Dog" << endl;

else

cout << "Cat" << endl;

//end if

return 0;

} //end of main function

 9.

//T8ConE09.cpp - displays a message based on the number entered by the user

#include <iostream>

using namespace std;

int main()

{

//declare variable

int entry = 0;

//enter input

cout << "Enter a number: ";

cin >> entry;

//display output

if (entry == 1 || entry == 2 || entry == 3)

cout << "Valid entry" << endl;

else

cout << "Entry error" << endl;

//end if

return 0;

} //end of main function

 10.

//T8ConE10.cpp - demonstrates the proper procedure for comparing float values

#include <iostream>

#include <cmath>

using namespace std;

int main()

{

//declare variables

float num1 = float(10.0);

float num2 = float (3.0);

float quotient = 0.0;

//calculate quotient

quotient = num1 / num2;

//compare for equality

if (fabs(quotient - 3.33333) < .00001)

cout << "Yes, the quotient " << quotient << " is equal to 3.33333" << endl;

else

cout << "No, the quotient " << quotient << " is not equal to 3.33333" << endl;

//end if

return 0;

} //end of main function

 

11.

//T8ConE11.cpp - demonstrates how to compare characters

#include <iostream>

#include <cctype>

using namespace std;

int main()

{

//declare variable

char letter = ' ';

//enter input item

cout << "Enter a letter: ";

cin >> letter;

//display output

if (toupper(letter) == 'P')

cout << "Pass" << endl;

else

cout << "Fail" << endl;

//end if

return 0;

} //end of main function

12. Changes made to the original code are shaded.

//T8ConE12.cpp - displays a message based on the age entered by the user

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variables

string name = "";

int age = 0;

//enter input

cout << "Enter your name: ";

getline(cin, name);

cout << "Enter your age: ";

cin >> age;

//display name and age

if (age > 21)

cout << name << " is over 21." << endl;

else

cout << name << " is not over 21." << endl;

//end if

return 0;

} //end of main function

 

13. Changes made to the original code are shaded.

//T8ConE13.cpp - displays a bonus

#include <iostream>

using namespace std;

int main()

{

//declare constant and variables

const float RATE = float(.1);

float sales = 0.0;

float bonus = 0.0;

//enter input

cout << "Enter the sales: ";

cin >> sales;

//display output

if (sales > 10000)

{

bonus = sales * RATE;

cout << "Bonus: " << bonus << endl;

}

else

cout << "Sorry, you do not get a bonus." << endl;

//end if

return 0;

} //end of main function

Solutions to Application Lesson Exercises

 

1.

IPO chart:

Input

Processing

Output

name

hours worked

pay rate

 

Processing items: none

Algorithm:

  1. enter the name, hours worked, and pay rate
  2. if (the hours worked is greater than 40)
  3. calculate the gross pay using the following expression: hours worked * pay rate + (hours worked – 40) * pay rate / 2

    else

    calculate the gross pay by multiplying the hours worked by the pay rate

    end if

  4. display the name and gross pay

name

gross pay

Desk-check table:

name

hours

rate

gross


Jack Henderson


Mary Matiez

0.0

35.0

0.0

45.0

0.0

10.0

0.0

7.5

0.0

350.0

0.0

356.25

///T8AppE01.cpp - displays an employee's gross pay

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variables

string name = "";

float hours = 0.0;

float rate = 0.0;

float gross = 0.0;

//enter input

cout << "Employee name: ";

getline(cin, name);

cout << "Hours worked: ";

cin >> hours;

cout << "Pay rate: ";

cin >> rate;

//calculate gross pay

if (hours > 40)

gross = hours * rate + (hours - 40) * rate / 2;

else

gross = hours * rate;

//end if

//display output

cout << fixed;

cout.precision(2);

cout << "Name: " << name << endl;

cout << "Gross pay: " << gross << endl;

return 0;

} //end of main function

 

2.

IPO charts:

main function

Input

Processing

Output

sales

 

Processing items: none

Algorithm:

  1. enter the sales
  2. bonus = calcBonus(sales)
  3. display the bonus

bonus

calcBonus function

Input

Processing

Output

sales

rate1 (10%)

rate2 (15%)

 

Processing items:

Algorithm:

  1. if (the sales > 12000)
  2. calculate the bonus using the following expression: 12000 * rate1 + (sales – 12000) * rate2

    else

    calculate the bonus by multiplying the sales by rate1

    end if

  3. return the bonus

bonus

 

Desk-check tables:

main function

sales

bonus

0.0

5000.0

0.0

96000

0.0

500

0.0

13800

calcBonus function

RATE1

RATE2

bonusAmt

.1

.1

.15

.15

0.0

500

0.0

13800

 

//T8AppE02.cpp - displays a bonus amount

#include <iostream>

using namespace std;

//function prototype

float calcBonus(float);

int main()

{

//declare variables

float sales = 0.0;

float bonus = 0.0;

//enter input

cout << "Enter the sales: ";

cin >> sales;

//assign bonus

bonus = calcBonus(sales);

//display bonus

cout << fixed;

cout.precision(0);

cout << "Bonus: " << bonus << endl;

return 0;

} //end of main function

//*****program-defined functions*****

float calcBonus(float dollars)

{

const float RATE1 = float(.1);

const float RATE2 = float (.15);

float bonusAmt = 0.0;

if (dollars > 12000)

bonusAmt = 12000 * RATE1 + (dollars - 12000) * RATE2;

else

bonusAmt = dollars * RATE1;

//end if

return bonusAmt;

} //end of calcBonus function

3.

//T8AppE03.cpp - displays the present value of a series of periodic payments

#include <iostream>

#include <cmath>

#include <fstream>

using namespace std;

int main()

{

const int PAYMENT = 360;

const int TERM = 48;

float rate = 0.0;

float principal = 0.0;

ofstream outFile;

outFile.open("T8AppE03.dat");

//enter input items

cout << "Enter the annual interest rate: ";

cin >> rate;

if (rate < 1)

rate = rate / 12;

else

rate = rate / 12 / 100;

//end if

//calculate present value (principal)

principal = PAYMENT * (1 - pow(rate + 1, -TERM)) / rate;

//display output items

cout << fixed;

cout.precision(0);

cout << "You can borrow up to $" << principal << endl;

outFile << fixed;

outFile.precision(0);

outFile << "You can borrow up to $" << principal << endl;

outFile.close();

return 0;

} //end of main function

 

Contents of T8AppE03.dat file

You can borrow up to $15329

4.

IPO charts:

main function

Input

Processing

Output

score 1

score 2

score 3

Processing items: none

Algorithm:

  1. enter score 1, score 2, and score 3
  2. if (score 1 >= 0 and score 2 >= 0 and score 3 >= 0)

calcAverage(score 1, score 2, score 3, average)

display the average

else

display an error message

end if

average

calcAverage function

Input

Processing

Output

score 1

score 2

score 3

address of average

Processing items: none

Algorithm:

  1. calculate the average by adding together score 1, score 2, and score 3, and then dividing the sum by 3

average

 

Desk-check tables: Unless specified otherwise, variables belong to the main function only.

main function

score1

score2

score3

average (main)

avg (calcAverage)

0.0

95.5

0.0

45.0

0.0

76.0

0.0

-78.0

0.0

59.0

0.0

30.0

0.0

76.8

0.0

calcAverage function

s1

s2

s3

95.5

76.0

59.0

//T8AppE04.cpp - displays the average of three numbers

#include <iostream>

using namespace std;

//function prototype

void calcAverage(float, float, float, float &);

int main()

{

float score1 = 0.0;

float score2 = 0.0;

float score3 = 0.0;

float average = 0.0;

//enter scores

cout << "Enter score 1: ";

cin >> score1;

cout << "Enter score 2: ";

cin >> score2;

cout << "Enter score 3: ";

cin >> score3;

//validate input

if (score1 >= 0 && score2 >= 0 && score3 >= 0)

{

//calculate average

calcAverage(score1, score2, score3, average);

//display average

cout << fixed;

cout.precision(1);

cout << "Average: " << average << endl;

}

else

cout << "All test scores must be positive numbers." << endl;

//end if

return 0;

} //end of main function

//*****program-defined functions*****

void calcAverage(float s1, float s2, float s3, float &avg)

{

avg = (s1 + s2 + s3) / 3;

} //end of calcAverage function

 

 5.

//T8AppE05.cpp - displays a water bill

#include <iostream>

#include <string>

using namespace std;

//function prototypes

void getInput(string &, int &, int &);

void calculate(int, int, float, int &, float &);

void displayBill(string, int, float);

int main()

{

const float RATE = float(.00175);

string name = "";

int current = 0;

int previous = 0;

int gallons = 0;

float charge = 0.0;

//enter input items

getInput(name, current, previous);

//validate input data

if (current > 0 && previous > 0 && current > previous)

{

//calculate gallons used and water charge

calculate(current, previous, RATE, gallons, charge);

//display water bill

displayBill(name, gallons, charge);

}

else

cout << "Error in input data." << endl;

//end if

return 0;

} //end of main function

//*****program-defined functions*****

void getInput(string &cust, int &cur, int &prev)

{

cout << "Customer name: ";

getline(cin, cust);

cout << "Current reading: ";

cin >> cur;

cout << "Previous reading: ";

cin >>prev;

} //end of getInput function

void calculate(int c, int p, float r, int &gal, float &due)

{

gal = c - p; //calculate gallons used

due = gal * r; //calculate water charge

} //end of calculate function

 void displayBill(string cust, int used, float amtDue)

{

cout << fixed;

cout.precision(2);

cout << "Customer name: " << cust << endl;

cout << "Gallons used: " << used << endl;

cout << "Water charge: " << amtDue << endl;

} //end of displayBill function

 6.

IPO chart:

Input

Processing

Output

number of registrants

rate (80)

 

Processing items: none

Algorithm:

  1. enter the number of registrants
  2. if (the number of registrants is greater than 0 and less than 50)

calculate the total owed by multiplying the number of registrants by the rate

display the total owed

else

display an eror message

total owed

 

Desk-check table:

RATE

registrants

totalOwed

80

80

0

5

0

-20

0

400

0

 

 //T8AppE06.cpp - displays a seminar charge

#include <iostream>

using namespace std;

int main()

{

const int RATE = 80;

int registrants = 0;

int totalOwed = 0;

//enter input items

cout << "Number of registrants: ";

cin >> registrants;

//validate input data

if (registrants > 0 && registrants < 50)

{

//calculate total owed

totalOwed = registrants * RATE;

//display total owed

cout << "Total: " << totalOwed << endl;

}

else

cout << "Error in input data." << endl;

//end if

return 0;

} //end of main function

 7.

IPO chart:

Input

Processing

Output

State

 

 

Processing items: none

Algorithm:

  1. enter the state
  2. if (the state is "Hawaii" or the state is "Oregon")

assign 30 as the shipping charge

display the shipping charge

else

display an eror message

shipping charge

 

Desk-check table:

state

shipCharge


Oregon


Kentucky

0

30

0

 

//T8AppE07.cpp - displays a shipping charge

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variables

string state = "";

int shipCharge = 0;

//enter input items

cout << "Enter state: ";

getline(cin, state);

//assign and display shipping charge

if (state == "Hawaii" || state == "Oregon")

{

//assign and display shipping charge

shipCharge = 30;

cout << "Shipping charge: " << shipCharge << endl;

}

else

cout << "Incorrect state" << endl;

//end if

return 0;

} //end of main function

8.

IPO chart:

Input

Processing

Output

state

Processing items: none

Algorithm:

  1. enter the state
  2. if (the state is "Alabama")
  3. assign 25 as the shipping charge

    else if (the state is "Alaska")

    assign 50 as the shipping charge

    else

    assign 0 as the shipping charge

  4. display the shipping charge

shipping charge

Desk-check table:

state

shipCharge


Alabama


Alaska


Illinois

0

25

0

50

0

0

 

//T8AppE08.cpp - displays a shipping charge

#include <iostream>

#include <string>

using namespace std;

int main()

{

//declare variables

string state = "";

int shipCharge = 0;

//enter input items

cout << "Enter state: ";

getline(cin, state);

//assign shipping charge

if (state == "Alabama")

shipCharge = 25;

else if (state == "Alaska")

shipCharge = 50;

else

shipCharge = 0;

//end ifs

//display shipping charge

cout << "Shipping charge: " << shipCharge << endl;

//end if

return 0;

} //end of main function

 

9. Changes made to the original code are shaded.

//T8AppE09.cpp - display a message based on the sales amount entered by the user

#include <iostream>

using namespace std;

int main()

{

//declare variable

int sales = 0;

//enter input

cout << "Enter the sales: ";

cin >> sales;

//display output

if (sales >= 10000)

{

cout << "Great job!" << endl;

cout << "You sold at least $10,000!" << endl;

} //end if

return 0;

} //end of main function