More Flow of Control: Multiway Branches (Section 7.2)

Consider the following:

if (shape == 'c' || shape =='C')
   cout << "Calculate volume of cube.\n";
else if (shape == 's' || shape == 'S')
   cout << "Calculate volume of sphere.\n";
else if (shape == 'b' || shape == 'B')
   cout << "Calculate volume of box.\n";
else
   cout << "Incorrect value entered.\n";

The switch statement:

A switch statement, like the if allows us to execute a different piece of code depending on the value of an expression that controls the switch.

switch (shape)
{
   case 's':
   case 'S':
      cout << "Calculate volume of a sphere.\n";
      break;
   case 'c':
   case 'C':
      cout << "Calculate volume of a cube.\n";
      break;
   case 'b':
   case 'B':
      cout << "Calculate volume of a box.\n";
      break;
   default:
      cout << "Incorrect value entered.\n";
      break;
}

Note:

This seemingly odd behavior allows us to have more than one label in front of a single piece of code. In fact we can have as many as we like.

More Loop Constructs

So far the only loop we've seen is the while loop. When the number of repetitions of a group of statements is fixed ahead of time we may use the for loop.

Consider the problem to calculate the product of integers from 1 to n (i.e. the factorial function):

n! = n*(n-1)*(n-2)* ... * 1

This may be implemented as follows:

int count = 1, product = 1;
while (count <= n)
{
  product *= count;
  count++;
}
cout << "The factorial of " << n << " is "
    << product << endl;

As soon as we know the value for n, we know the number of times we want to execute the while loop. In such cases, we may use another C++ looping construct, the for loop.

The general form of the for loop is:

for (initialization; logical_expression; update)
   body

where:

We may implement thus:

int product = 1;
for (count=1; count <= n; count++)
  product *= count;
cout << "The factorial of " << n << " is "
<< product << endl;

Examples:

sum = 0;
for (i = 10; i >= 1; i--)
   sum += i;

The body can be a single statement or a compound statement.

sum = 0; product = 1;
for (i = 1; i <= 10; i++)
{
  sum += i;
  product *= i;
}

The break statement in loops:

Our text talks about using the break statements to end loops. In this class, this will NOT be done. Your assignments should always be designed so that you exit loops gracefully, without using a break.

Note that you can nest for loops. Examine the following example.

int i,j,num;
long sum = 0;
cout << "Enter an integer: ";
cin >> num;
for (i=1; i <= num; i++)
   for (j=1; j <= i; j++)
    sum += j;
cout << "\nThe double sum is " << sum << endl;

The value for sum when num = 0 is 0; when num = 1 is 1; num = 2 is 4; num = 3 is 10; num = 4 is 20

Predefined functions

The sqrt function:

double sq_root;
sq_root = sqrt (9.0);
cout << "Square root of 9.0 is " << sq_root;

The expression sqrt (9.0) is a function call. You can use a function call anywhere C++ expects an expression.

cout << "Square root of 9.0 is " << sqrt (9.0);

The value in the input (9.0) is called the argument to the function. The result that is returned is called the returned value. A function can take one or more (or no) arguments, but it always produces at most one value. In particular, a function cannot return more than one value.

You can give a function any expression as an argument

double first_num = 3.0, second_num = 1.0;
cout << "Square root of" << first_num + second_num
    << " is " << sqrt (first_num + second_num);

Note that both the input and the returned value must be of the correct type, otherwise you will get a type error. sqrt returns a double so that the following would cause a type error.

int int_val;
int_val = sqrt (9.0);

If you want to use a pre-defined function, you need to include the library that contains it. For example, if you want to use sqrt you will need #include <math.h> (i.e. include directive - see page 111 and Appendix 4 for additional examples of functions and header files)

Example: if you want to compute xy then:

result = pow(x,y);

This is an example of the pow function which returns a value of type double.

Note: Be careful when using pow with negative numbers since when the base x is negative, some compilers require that the exponent y be a whole number. In general it's a good idea to make sure that the type of the arguments used is correct for the function.

Type Changing Functions

Consider the following. Compute a student’s class average.

#include <iostream.h>
int main()
{
  int course_pts = 450, possible_pts = 500;
  double average;
  average = course_pts / possible_pts;
  cout << "The average is " << average << endl;
  return 0;
}

Notice that average will be 0.00 instead of 0.90. The possible points in the course are whole numbers, so there is no point in declaring either course_pts or possible_pts as double. C++ has type casting functions that let us convert (i.e. sometimes referred to as cast) the value of one of the variables to double, thus forcing the division to be a floating-point division.

average = course_pts / double(possible_pts);

In general to change from one type to another you need to write:

type (expression of other type);

e.g.: double(possible_pts)

e.g.: int(3.5)

  Programmer Defined Functions

You can define your own functions either in the same file as the main part of your program or in a separate file so that several different programs can use them. For now we'll just concern ourselves with writing functions that are in the same file as the main part of the program.

Functions have two parts:

Consider a summation program to compute the sum of squares of numbers from 1 to n.

#include <iostream.h>
int square (int number);
// Function Prototype
int main ()
{
   int i,n, sum_squares = 0;
   cout << "This calculates the sum of squares "
      << "of the numbers from 1 to n.\n"
      << "Please enter the value of n: ";
   cin >> n;
   for (i = 1; i <= n; i++)
     sum_squares += square(i);
   cout << "The sum of the squares from 1 to "
       << n << " is " << sum_squares << endl;
   return 0;
}
int square (int number)
// Function Definition
{
  return (number * number); // Here, it is
}

Additional Terminology:

e.g.: int square (int n);

Example:

The following program incorporates all the ideas covered so far:

#include <iostream.h>
double box_vol(double height, double depth, double width);
//computes hgt x depth x width
int main()
{
  char answer;
  double box_height, box_width, box_depth, side;
  cout << "Which do you want to compute?\n"
      << "\t(C)ube or\n" << "\t(B)ox\n";
  do
  {
     cout << "Your choice: ";
     cin >> answer;
     switch (answer)
     {
       case 'c':
       case 'C':
         cout << "\nYou selected 'Cube'\n";
         cout << "Enter the lenght of a side: ";
         cin >> side;
         cout << "A cube, side " << side << " has volume "
            << box_vol(side, side, side) << endl;
         break;
       case 'b':
       case 'B':
         cout << "\nYou selected 'Box'\n";
         cout << "Enter the height, depth and width: ";
         cin >> box_height >> box_depth >> box_width;
         cout << "A box, dimension " << box_height << " x "
            << box_depth
            << " x " << box_width
            << " has volume " << box_vol(box_height, box_depth, box_width)             << endl;
         break;
       default:
         cout << "'" << answer << "' is not a valid selection."
            << "\nTry again\n\n";
     }
   } while (answer != 's' && answer != 'c' && answer != 'b' &&
        answer != 'S' && answer != 'C' && answer != 'B');
   cout << "Goodbye!\n\n";
   return 0;
}
double box_vol(double height, double depth, double width)
//computes hgt x depth x width
{
   return (height * depth * width);
}