CS 1425 Lab 2 - C++ Simple Flow of Control

Motivation

The order in which statements are executed is the flow of control. So far in the programs you have written, each and every statement you write gets executed one after the other. To write more sophisticated programs, we will need to alter this sequential flow of control. This lab says to try a lot of different programs. You don't have to try each one if you know what the output will be. But, pay close attention to the syntax.

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.

Agenda

Here is the schedule for this lab on the IF-ELSE and WHILE statements. Just click on each item to do that section.

  1. Log on
  2. IF-ELSE statement basics
  3. IF-ELSE statement examples
  4. IF-ELSE statement pitfalls
  5. IF-ELSE lab work
  6. WHILE statement basics
  7. WHILE statement examples
  8. WHILE statement pitfalls
  9. WHILE lab work
  10. Homework

Log on


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:
cout << "The largest value is " << x;
And if y is the larger value your C++ output statement would look like:
cout << "The largest value is " << y;

The problem then becomes how to make the program decide which of these statements to execute (based on the values of x and y)?

The IF-ELSE statement to the rescue!

Here is the C++ statement to do exactly what we want:

if (x > y)
cout << "The largest value is " << x;
else
cout << "The largest value is " << y;

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:

if   (Logical_Expression)
Yes_Statement
else
No_Statement

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
x > y

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.

if   (Logical_Expression)
Yes_Statement

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.

if   (Logical_Expression)
{
Yes_Statement_1
Yes_Statement_2
. . .
Yes_Statement_Last
}
else
{
No_Statement_1
No_Statement_2
. . .
No_Statement_Last
}

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.

Comparison Operators
C++ operatorEnglishC++ example
==equal tox+x == 2*x
!=not equal toanswer != 'N'
<less thancount < 3
<=less than or equal totime <= limit
>greater thantime > limit
>=greater than or equal toage >= 21

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,

(x > 2) && (x < 7)

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,

(y < 0) || (y < 3)

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.

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!!";
}

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.

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* 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.

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:

while  (count_down > 0)
{
cout << "Hello ";
count_down = count_down - 1;
}

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.
Value of count_down Output
0 
1Hello
3Hello Hello Hello

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.

/* 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;

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:


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

Modifying this program is part of your homework.

Practice Assignment

  1. Write a C++ program called add30.C that asks the user for a starting integer value n, adds 30 successive integers starting with that value, and displays the sum. For example, if the user enters 40, you would find the sum 40 + 41 + 42 + ... + 69. In this case the program would print 1635. (HINT: You could use a loop that runs 30 times. Each time through the loop you should add the user's input plus a count onto the accumulating sum. The count should be zero the first time through the loop so that only the user's input gets added on.)