Branching

Exercise 1 - Input Data Validation

The following program inputs a cat's age in years and converts it to a human scale age. 

//**********************************************************
// Program 1 : Cat Age Conversion
// Programmer: Your Name
// Completed : 6/25/98
// Status    : Complete
//
// This program calculates the age of a cat on a human scale.
//***************************************************************

#include <iostream.h>
#include <iomanip.h>

const float CAT_TO_HUMAN = 6.5;  // Cat years to human years
			       //    conversion factor

int main()
{
   float catYears;     // cat's age in years
   float humanYears;   // cat's age on human scale

// Set up floating point output format
   cout.setf(ios::fixed, ios::floatfield);
   cout.setf(ios::showpoint);
   cout << setprecision(1);

// Get the cat's age in years
   cout << "Enter cat's age in years: ";
   cin  >> catYears;

// Calculate the cat's age on a human scale
   humanYears = CAT_TO_HUMAN * catYears;

// Print the cat's actual age and human age
   cout << "If the cat actual age in years is "
        << catYears << "," << endl;
   cout << "it's age in human years is "
        << humanYears << "." << endl;
   return 0;
}

Exercise Steps:

  1. Make a copy of the program above, paste it into your C++ editor, and run it.
  2. Describe the output.
  3. Try running your program again with an input age of -4.7. Does your input make sense? Does the output make sense?

Input data should be checked to verify that the input value falls into a reasonable range of values. A negative value for an age really does not make any sense. Also, most cats live less than 20 years. So an age of 33 is probably not a reasonable input value either. When an input value that is outside a reasonable range is entered, your program should not try to process that input. It should just print a message indicating what range of input values are acceptable.

Exercise Steps (continued):

  • Modify your program to check for negative ages. If a negative age is entered, your program should print the age entered and a message with the acceptable range of ages, and end. It should not perform the age conversion or print the converted age. If a good age is entered, it should work the same as before.
  • Print a copy of your new program.
  • Print a sample of your program output for valid input.
  • Print a copy of your program output for invalid input.
  • Try to modify your program so that it checks for both negative ages and ages over 30 years. Change your messages as appropriate.
  • When you have completed this exercise, click here to check your answers.