Selection statements allow the program to perform different statements based on some condition. The condition usually consists of a comparison of two or more values. Simple comparisons are performed with relational operators. In C++ the relational operators are:
Symbol | Meaning |
== | equal |
!= | not equal |
< | less than |
> | greater than |
<= | less than or equal to |
>= | greater than or equal to |
Here are some examples of pseudocode for selection operations:
read time if time is 5pm print "go home" read gender if gender is female print "Dear Madam" else print "Dear Sir" read cholesterol if cholesterol >= 200 print "your cholesterol is too high" print "please see your doctor" else if cholesterol >= 190 print "be careful...your cholesterol is borderline" else print "your cholesterol is ok"
Notice that we indent the statement(s) that come after the if, and the statement(s) that come after the else. Without this the program is very difficult to read.
In C++, the condition in an if statement is always enclosed in parentheses. If more than one statement is needed after the if or the else, they must be surrounded by braces { }, If only one statement is needed after the if or the else, then braces are optional. Here are some examples of C++ code containing if statements:
cout << "Enter f for female or m for male: "; cin >> gender; if (gender == 'f') cout << "Dear Madam"; else cout << "Dear Sir"; cout << "Enter department number: "; cin >> deptnum; cout << "Enter item cost: "; cin >> cost; if (deptnum == AUDIO) // audio items are 10% off cost = cost * .9; tax = cost * taxrate; totalcost = cost * tax; cout << "Enter department number: "; cin >> deptnum; cout << "Enter item cost: "; cin >> cost; if (deptnum != VIDEO) // all items except video are 15% off cost = cost * .85; tax = cost * taxrate; totalcost = cost * tax; cout << "Enter item cost: "; cin >> cost; if (cost <= 200) cost = cost * .92; // items under $200 are 8% off else cost = cost * .88; // items over $200 are 12% off tax = cost * taxrate; totalcost = cost * tax;
Email Me |
Office Hours |
My Home Page |
Department Home |
MCC Home Page
© Copyright Emmi Schatz 2002