If you want to print this lab, print the version you get when you click here: Printing Version of Lab #3
Sometimes you may need your program to decide to execute one statement and not another. The IF-ELSE statement provides this branching capability. At other times, you may wish to execute a statement more than once. The WHILE statement provides such a looping mechanism.
To get started, the first thing you need to do is log onto cs and arrange the cs window so that changing between it and the Netscape window is easy. Go do that now.
Next, change to your 1425 class directory on cs and create a new project directory. Call it "lab3". Now change to that new directory.
Return to Agenda
IF-ELSE Statement basics
Sometimes it is necessary to have a program choose one of two
alternatives, depending on some condition. For example, suppose your
program has to output the larger of two integers, x or
y. Well, if x is the larger value your C++ output
statement would look like:
The problem then becomes how to make the program decide which of these
statements to execute (based on the values of x and
y)?
Here is the C++ statement to do exactly what we want:
This is the most complex statement we've encountered in C++, so please
follow this link for an explanation of the
IF-ELSE statement
IF-ELSE Statement syntax
The basic syntax of the C++ IF-ELSE statement is:
The two embedded statements may be any executable statements. The
Logical-Expression is some test that can be checked to see if
it is true or false. The Logical-Expression in our example
was
When the program reaches an IF-ELSE statement, exactly one of the two
embedded statements are executed. If the Logical-Expression is
true then Yes_Statement is executed; if the
Logical-Expression is false then the No_Statement is
executed.
Every IF-ELSE statement must have a Logical_Expression so let's
talk a little about logical expressions.
A simpler variation of the IF-ELSE statement is when you don't want to
do anything in the No_Statement. In this situation the
else part can be omitted altogether. For example, to abort if
there is a malfunction detected.
A more complicated variation of the IF-ELSE statement is when you need
to execute more than one statement based on the logical expression.
In this case the Yes_Statement and/or the No_Statement
can be a compound statement. A compound statement is a list of
statements enclosed in a pair of braces. A compound statement is
treated as a single statement by C++ and can be used anywhere that a
single statement can be used.
Return to Agenda
Logical Expressions
A logical expression is any expression that can be tested to
see if it is true or false; that is, tested to see if it is satisfied
or not satisified.
The simplest form of a logical expression consists of two expressions
that are compared with a comparison operator. The operators are shown
in the table below. Note that some of the operators are two symbols
and that no space is allowed between the two symbols.
You can build logical expressions by combining two comparisons using
the "and" and "or" operators. The C++ operator for "and" is
&& and || is the C++ operator for "or."
When combining two comparisons with && , the entire expression
is true provided both of the comparisons are true. For
example the combined expresssion,
is only true when (x > 2) is true AND (x <
7) is true. Thus, this expression is true when x has
the values 3, 4, 5, or 6. When x has the value 7, the
comparison (x > 2) is true because 7 is greater than 2.
But (x < 7) is false since 7 is not less than 7 (it is
equal). Since both comparisons were not true, the entire expression
is false.
When combining two comparisons with ||, the entire expression
is true provided one or both of the comparisons are true. For
example the combined expresssion,
is true when (y < 0) is true AND/OR (y <
3) is true. Thus, this expression is true when y has
any negative value, 0, 1, and 2. When y has the value -1, the
comparison (y < 0) is true and (y < 3) is also
true. Hence, the entire expression is true. When y has the
value 0, the
comparison (y < 0) is false, but (y < 3) is
true. And again, the entire expression is true.
When y has the
value 3, the
comparison (y < 0) is false, and (y < 3) is also
false. Since neither comparison is true, the entire expression is false.
Return to IF-ELSE Statement syntax
IF-ELSE Statement examples
Here are some examples of correct IF-ELSE statements. Of course, the
output depends on the values of the variables used in the logical
expressions. Try out a couple of these examples by creating a small
program and copying-and-pasting in the example code. Be sure that vi
or vile is in insert mode before you paste! To complete a program
you will have to
declare and give values to each of the variables. Investigate what
output results from different variable values. If you build your
program so that it reads the values for the variables at run-time using
cin, you won't have to recompile it just to change the values of the
variables.
Return to Agenda
IF-ELSE Statement pitfalls
There are several pitfalls that a programmer can make when using the
IF-ELSE statement.
Return to Agenda
IF-ELSE lab work
Using copy and paste, copy the program below into file taxes.C in
your lab3 subdirectory.
Next, modify the program so that it calculates the taxes on a sliding
rate. If the gross_pay is less than $20,000 than the rate is 7.5%.
If the gross_pay is $20,0000 or greater and less than $40,000, than
the rate is 18.5%. If the gross_pay is $40,000 or greater, than
the rate is 33.0%. (Be sure to modify the program header.)
Modifying this program is part of your homework. You will submit a copy
of this program along with the rest of your homework.
Return to Agenda
WHILE Statement basics
Imagine a payroll-type program that needs to compute the wages for 100
workers. You could write the statements needed to compute the wages
for one worker and then copy-and-paste those statements 99 times.
Yuck. Luckily, there is a much easier way to repeat a statement
(or group of statements). C++ provides a looping mechanism with its
WHILE statement.
Here is a simple example:
The body of the loop is the compound statement containing two
statements. The loop body is repeated as long as the logical
expression is true. The logical expression in this example is
count_down > 0. Notice that the loop body changes the
value of count_down and this new value is used in the next
evaluation of the logical expression.
It is important to remember that the logical expression of the WHILE
statement is evaluated prior to the loop body each time. If
and when the logical expression becomes false, the loop body is
not executed and the WHILE statement is finished.
So for our simple example, the output produced by the loop is shown in
the table below for different initial values of count_down.
Return to Agenda
WHILE Statement examples
Here are some examples of correct WHILE statements. Try out a
couple of these examples by creating a small
program and copying-and-pasting in the example code. Make sure to
declare and give values to each of the variables.
Return to Agenda
WHILE Statement pitfalls
There are several pitfalls that a programmer can make when using the
WHILE statement.
Return to Agenda
WHILE lab work
Copy the taxes.C program that you worked on earlier into the
file taxeslp.C (for "taxes loop"). Modify the program so that
it continues to perform calculations as long as the gross income
is positive. Thus the user can enter a negative or zero gross income
to get the program to stop. Here's a sample run:
Modifying this program is part of your homework.
Return to Agenda
In addition to the two programs you completed earlier in this lab,
write the following two programs.
And if y is the larger value your C++ output
statement would look like:
The IF-ELSE statement to the rescue!
Comparison Operators
C++ operator English C++ example
== equal to x+x == 2*x != not equal to answer != 'N' < less than count < 3 <= less than or equal to time <= limit > greater than time > limit >= greater than or equal to age >= 21
if ( (temperature >= 95) || (humidity >= 90) )
cout << "Whew! Where is some AC?";
if ( x > -1 && x < 1 )
cout << "x is zero!!";
else
cout << "x is non-zero!!"
if ( time > limit )
{
overlimit = overlimit + 1;
cout << overlimit << " times over the limit.";
}
if ( time != alarm )
time = time + 1;
else
{
time = time + 1;
cout << "Wake up!!";
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Program: taxes.C
* Date: <today's date>
* Programmer: <your name>
*
* This program calculates taxes and net income, assuming a tax rate
* of 7.5% and given a gross income provided by the user.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <iostream.h>
int main()
{
double gross_pay, /* gross pay entered by the user */
net_pay, /* pay after taxes */
rate, /* rate at which to tax */
taxes; /* amount to be paid in taxes */
rate = .075; /* 7.5% */
/* make double values be printed with two places after decimal point */
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "\n\nHi. This program calculates net pay after taxes.\n";
cout << "You'll be prompted for gross income then the program will tell\n"
<< "you how much you'll pay in taxes and your net income.\n\n";
cout << "Please enter gross income: $";
cin >> gross_pay;
taxes = gross_pay * rate;
net_pay = gross_pay - taxes;
cout << "\nNet income: $" << net_pay;
cout << "\nTaxes to pay: $" << taxes << endl;
return 0;
}
Run the program several times to get a feel for what it does.
Note that it will not run correctly if the data entered is incorrect.
Value of count_down
Output
0 1 Hello 3 Hello Hello Hello
/* Print the numbers 5 through 9: */
i=5;
while (i < 10)
{
cout << i;
cout << endl;
i = i + 1;
}
/* Finding the sum 1 + 2 + 3 + ... + 20 */
i = 1;
sum = 0;
while (i <= 20)
{
sum = sum + i;
i = i + 1;
}
cout << "The sum is " << sum;
/* Average a list of grades terminated by -1 */
sum = 0;
count = 0;
cout << "Enter grade (-1 to end): "; // prompt user for grade
cin >> grade; // read grade
while (grade != -1)
{
sum = sum + grade;
count = count + 1;
/* Get next grade */
cout << "Enter grade (-1 to end): ";
cin >> grade;
}
if (count > 0)
cout << "Average is " << (double) sum / count;
Hi. This program calculates net pay after taxes.
You'll be prompted for gross income and then
the program will tell you how much you'll pay in taxes
and your net income.
Please enter gross income (0 to stop): $19000.00
Net income: $17575.00
Taxes to pay: $1425.00
Please enter gross income (0 to stop): $0
Practice Exercise
Return to Agenda