BIG C++
Cay Horstmann & Timothy Budd

Laboratory Notebook
Chapter 7 - Advanced Flow Control


Your name:
Your email address:
Your student ID number:

Once this form has been customized for your institution, you can use this button to send your lab work. Be sure to read the instructions before starting your work.


Lab Objectives

To gain experience in


P1. Multiple Alternatives

The if/else decision for electric rates that was implemented in the Chapter 4 lab can be extended to select from more than two possible outcomes. The if ... else if . . else syntax is used to select exactly one of several possible actions.

if (condition1)
   /* do something ... */
else if (condition2)
   /* do something different ... */
else
   /* do something generic ...   */

Write a program to compute the electric bill as you did above.  Instead of two rates, write the program so that there are 4 different rates as follows:

0-999 KWH $0.60
1000-1499 KWH $0.45
1500-1999 KWH $0.40
2000 or more KWH $0.35

     


P2. Nested Branches

If there are multiple conditions, it can happen that a conditionally executed block contains further decisions.  For example, let's suppose that our electric rates were based upon certain rate classes within each grouping:

            0 - 999 KWH   
                commercial rate class  $0.49
                r1 rate class                $0.57
                r2 rate class                $0.60

            1000-1499 KWH                
                commercial rate class  $0.38
                r1 rate class                $0.43
                r2 rate class                $0.44
                r3 rate class                $0.45

            1500 - 1999 KWH
                commercial rate class  $0.31
                r1 rate class                $0.40
      
            2000 or more KWH  
                 commercial rate class  $0.29
                 r1 rate class                $0.31
                 r2 rate class                $0.35

Modify the program that you wrote for P4 to perform the computations based upon the rate classes.


P3. Logical Operations

C++ has three logical operations, and, or and not. These are traditionally written as &&, || and !. Both variants are legal under ANSI C++. We find the former easier to read, but many C++ programmers use the latter out of habit. Feel free to use either form in your answers.

Using these operations, express the following:

x and y are both positive or neither of them is positive.

The following program calculates the discount rate for fuel oil.  Simplify the nested branches by using Logical Operations and, or, not wherever possible.

#include <iostream>
#include <string>
using namespace std;
int main()
{  
	string  customer_city;
	double	gal_last;
	double discount_rate  =  1;
	cout <<"Customer City:";
	getline(cin,customer_city);
	cout <<"Number of gallons of oil used last year: ";
	cin >>gal_last;
	if (customer_city == "Boston")
		if (gal_last >= 1000)
				discount_rate = .9;
		else
				discount_rate = 1;
	else if (customer_city == "Worcester")
		if (gal_last >= 1200)
				discount_rate = .91;
		else
				discount_rate = 1;
	else
		if (gal_last >= 1500)
			discount_rate = .9;
		else
			discount_rate = 1;
	cout << "Discount rate is:   "<<discount_rate;
	return 0;
}


P4. for Loops

A variable that counts the iterations of a loop is called a loop index.  Looping can be accomplished with a loop index and a while loop or we can use the a for loop, with the following syntax:

for ( loop_index = start_value ; condition ; index_increment )

Write a program controlled by two for loops which produces the following listing of inclusive dates, from the 5th Century B.C. through the 5th Century A.D.

Century 5 BC  400-499
Century 4 BC  300-399
Century 3 BC  200-299
Century 2 BC  100-199
Century 1 BC  1-99
Century 1 AD  1-99
Century 2 AD  100-199
Century 3 AD  200-299
Century 4 AD  300-399
Century 5 AD  400-499

Write the same program with a single loop for( i = -5 ; i <= 5 ; i++ ) and an if in the body of the loop.


R1. Other Loops

One loop type might be better suited to a purpose than another. The following usages are idiomatic.

for Known number of iterations
while Unknown number of iterations
do while At least one iteration

Convert to a do while loop

/* PURPOSE: Program to compute a running sum of user-input integers
*/

#include <iostream>
using namespace std;

int main()
{  int sum = 0;
   int n = 1;
   
   while( n != 0 )
   {  cout << "Sum =  " << sum  << "\n";
      cout << "Please enter a number, 0 to quit ";
      cin >> n;

      sum += n;
      cout << "Sum =  " << sum  << "\n";
   }
   return 0;
}

Is this an improvement? Why?

Convert the inner while loop to a for loop

/* PURPOSE: Program to compute the first integral power to which 2 can be 
            raised that is greater than that multiple of a user-input integer. 
*/

#include <iostream>
using namespace std;

int main()
{  int i = 1;
   int n = 1;

   while(true)
   {  cout << "Please enter a number, 0 to quit ";
      cin >> n;
      if (n == 0) return 0;
      i = 1;
      while ( n * n > pow(2,i))
      {   i++;
      }
      cout << "2 raised to " << i 
         << " is the first power of two greater than " << n << " squared\n";
   }      
}

Is this an improvement? Why?

Convert to a while loop:

#include <iostream>
using namespace std;

int main()
{  int i;

   for(i = 1; i <= 10; i++)
   {  cout << i << " squared equals " << i * i << "\n";
   }
   return 0;
}

Is this an improvement? Why?


P5. Iterating Through a String

Many word-processors can check spelling. One of the corrections applied is to swap 'e' for 'i' if 'i' occurs immediately before 'e' and immediately after 'c'. For example, concieve is corrected to conceive. Complete a function string i_before_e(string word) that carries out this correction. That is, your function should return the corrected string (or the original string if no correction needed to be applied.)

string i_before_e(string word)
{  string r = "";
   for (i = 0 ; i < word.length() ; i++ )
   { /*
        Your work goes here
     */
   }
   return r;
}

Write a test harness to test the preceding function by feeding it many inputs.

#include <iostream>
#include <string>
using namespace std;

int main()
{  bool done = false;
     
   while (not done)
   {  /*
         Your work goes here
      */
   }
   return 0;
}


R2. Tracing Loops

1) What is the output of each of the following loops?

2) In each example, leave the loop as it is and change the expression following cout << so that the program will display "1 2 3 4 5 ".

#include <iostream>
using namespace std;

int main()
{  for ( i = 0 ; i < 5 ; i++ )
   {   cout << i << " ";
   }
   cout << "\n";
   return 0;
}

#include <iostream>
using namespace std;

int main()
{  int decimals = 1;
   while (decimals < 100000)
   {  cout << decimals << "\n";
      decimals *= 10;
   }
   return 0;   
}

#include <iostream>
using namespace std;

int main()
{  int i = 5;
   do
   {  cout << i << "\n"
      i--;
   }  while( i > 0 )
   return 0;   
}


P6. Nested Loops

Write a program to draw a top view of 24 soda cans, that is 24 circles, arranged in a 4 x 6 grid like this:

4 by 6 Beercans


P7. Processing Text Input

Write a program to read sentences entered by the user. The user should terminate the sentence by entering a /n. Your program should count the number of words in the sentence and ask the user if they would like to enter another sentence. It should keep track of the number of words in the sentence and compare it to the greatest number of words counted in one sentence up to that point. If it exceeds the greatest, the number of words for the new sentence becomes the greatest.



Do not forget to send your answers when you are finished.