BIG C++
Cay Horstmann & Timothy Budd

Laboratory Notebook
Chapter 4 - Basic Control Flow


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


R1. The if statement

In C++, decisions to execute or not execute a statement or group of statements can be made by using the statement if (condition). The condition must be an expression that can be evaluated as either true or false. If it evaluates to true, a succeeding statement or group of statements enclosed in { . . . }, called a block statement will be executed.

In the example below:

How much money will be added to your account when the initial starting amount is $100?

How much money will be added to your account when the initial starting amount is $85?

#include <iostream>

int main()
{ 
    
    
  double initial_value, final_value;
  cout <<"Please enter the initial balance: ";
  cin >> initial_value;
    if (inital_value > 90 )
    {  
      final_value = final_value + 10;
    }

    final_value = final_value + 5;
    cout <<"Final Value" <<final_value;
    return 0;
}

R2. Relations and Relational Operators

The relational operators in C++ are == != < > <= and >=

Formulate the following conditions in C++:

x is positive
x is zero or negative
x is at least 8
x is less than 8
x and y are both zero

Formulate the following conditions for the employee object e.

The last name of e starts with the letter H
The salary of e is at least $75,000

Formulate the following conditions on the variable harrys_birthday of type Time.

Harry is at least 21 years old.
Harry was born in August.
Harry was born in a leap year (assume his birthday was between 1901 and 2099).


P1. Input validation

Build and run the following program. Describe what happens when the two points have the same x coordinate?

#include <iostream>
using namespace std;
#include "ccc_shap.cpp"
main()
{  double slope;

   double xcoord, ycoord;
   Point p1, p2; 

   cout << "Input x coordinate of the first point" << "\n";
   cin >> xcoord;
   cout << "Input y coordinate of the first point" << "\n";
   cin >> ycoord;

   p1 = Point(xcoord, ycoord);

   cout << "Input x coordinate of the second point" << "\n";
   cin >> xcoord;
   cout << "Input y coordinate of the second point" << "\n";
   cin >> ycoord;

   p2 = Point(xcoord, ycoord);

   slope = (p2.get_y() - p1.get_y()) / (p2.get_x() - p1.get_x() );

   cout << "The slope of the line between Points 1 and 2 is " << slope << "\n";
   return 0;
}

Correct and rebuild the program to disallow a vertical line (denominator = 0).

What are the results when point1=(4,2) and point2 = (4,2) ?

What are the results when when point1=(4,2.5) and point2 = (3,1.5) ?


P2. Additional Input Validation Exercise

Build and run the following program. Describe what happens when the salaries from the first and second years are equal.

#include <iostream>
    using namespace std;
    int main()
    { 
   double fyear_sal, syear_sal,tyear_sal;

   cout << "Input the first year's salary:" << "\n";
   cin >> fyear_sal;;
   cout <<  "Input the second year's salary:" <<  "\n";
   cin >> syear_sal;
   cout << "Input the third year's salary:" << "\n";
   cin >> tyear_sal;
   cout <<  "The difference between the third and second year salary and second and first is:"
    cout << ((tyear_sal-syear_sal)/(syear_sal-fyear_sal))*100 << "%";
   return 0;
    }
    

Correct and rebuild the program to not allow for case where both the first and second year salaries are the same.

What are the results when fyear_salary = 100000 and syear_salary = 100000?



P3. The if/else Statement

In the previous examples, your program probably responded to user input by ignoring cases that would result in a divide by zero. Instead, you can use the if/else format to explicitly specify the action to be taken.

if (condition)
   /* do something ... */
else
   /* do something different ... */

The electric company gives a discount on electricity based upon usage. The normal rate is $.60 per Kilowatt Hour (KWH). If the number of KWH is above 1,000, then the rate is $.45 per KWH. Write a program that prompts the user for the number of Kilowatt Hours used and then calculates and prints the total electric bill.

According to your program, how much will it cost for:

900 KWH?
1,754 KWH?
10,000 KWH?

P4. Simple Loops

Frequently a decision needs to be made whether or not to do something again. Here is a program that computes the number of digits needed to represent a number in base 10, just like the function digits() from the preceding lab. But instead of using recursion it uses multiple if statements.

/* PURPOSE:  Count number of digits needed to express an integer in base 10
             using multiple if statements
   REMARKS:  Compare to Ch.5 digits()
*/

#include <iostream>
using namespace std;

int main()
{  int input;

   cout << "Input an integer between 1 and 9999: ";
   cin >> input;

   int temp = input;
   int d = 1;

   assert ( input >= 1 and input <= 9999 );
    
   if (temp > 9)
   {  temp = temp / 10;
      d++;
   }
      
   if (temp > 9)
   {  temp = temp / 10;
      d++;
   }

   if (temp > 9)
   {  temp = temp / 10;
      d++;
   }

   if (temp > 9)
   {  temp = temp / 10;
      d++;
   }
   
   cout << input << " can be expressed in " << d << " digits" << "\n";
   
   return 0;
}

But having to write

   if (temp > 9)
   {   temp = temp / 10;
       d++;
   }

four times, even using copy/paste, is clearly repetitive! It also only works for input <= 9999. One would like to have a way of testing that the input is still greater than 1 and executing the succeeding control block if it is. Replacing if with while does it.

/* PURPOSE:  Count number of digits needed to express an integer in base 10
             using while loop
*/

#include <iostream>
using namespace std;

int main()
{  int input;
  
   cout << "Input an integer: ";
   cin >> input;
   int d = 1;
   int temp = input;

   while (temp > 9)
   {  temp = temp / 10;
      d++;
   }

   cout << input << " can be expressed in " << d << " digits" << "\n";   
}


The fractions 1/2, 1/4, 1/8, ... get closer and closer to 0. Change the previous program to count the number of divisions by two needed to be within 0.0001 of zero.


P5. Loop Termination

Which values of nyear cause the following loops to terminate?

/* PURPOSE: Count number of year between a user-input year and the
            year 2000.
*/            

int main()
{  int nyear;
   millennium = 2000;
   
   cout << "Please enter the current year";
   cin >> nyear;
   
   while (nyear != millennium)
   {  nyear++;
   }
   
   cout << " Another "<< millenium - nyear << "years to the millenium." << "\n";
   return 0;
}
   

Re-write the preceding program so that the while loop will terminate for any integer input.


P6. Processing a Sequence of Inputs

Modify the electricity rate program to allow the user to enter data for any number of months.  The user should be able to enter a -1 when finished. The program should then compute the cost using the same formulas as above.


R3. Using Boolean Variables

According to the following program, what color is the resulting mixture under the following inputs?

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

int main()
{  string mixture;      
   bool red, green, blue;
   string string_bool;

   cout << "Include red in mixture? (y/n) " << "\n";
   cin >> string_bool;
   if (string_bool == "y")
      red = true;
   cout << "Include green in mixture? (y/n) " << "\n";
   cin >> string_bool;
   if (string_bool == "y")
      green = true;
   cout << "Include blue in mixture? (y/n) " << "\n";
   cin >> string_bool;
   if (string_bool == "y")
      blue = true;

   if (not blue and not green)     
      mixture = "RED";
   else if (not red and not blue)     
      mixture = "GREEN";
   else if (not red and not green)     
      mixture = "BLUE";
   else if (red)
   {  if (green or blue)
      {  if (green and blue)
            mixture = "BLACK";
         else if (green) 
            mixture = "YELLOW";
         else
            mixture = "PURPLE";
      }
   }
   else
   {  if (blue and green)
         mixture = "CYAN";
      else
         mixture = "WHITE";
   }
   cout << "Your mixture is " << mixture << "\n";

   return 0;
}

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