Exiting main() early

The "return 0;" at the end of your program exits your program. In fact, inside main you can stick a "return 0;" wherever you want and as often as you want, and it'll exit the program.

For example, maybe you want to write a program that reads an integer k from the user and writes out 1/k. If the user enters zero, of course, there's a problem. Now we'll just castigate the user and exit the program if he does that!

#include <iostream>
using namespace std;

int main()
{
	// Get number from user
	cout << "Enter a non-zero integer: ";
	int k;
	cin >> k;

	// Deal with bad input
	if (k == 0)
	{
		cout << "You really should read and follow the directions!" << endl;
		return 1;
	}

	// Write out decimal approximation of 1/k
	cout << "1/" << k << " is " << 1/double(k) << endl;

	return 0;
}
You may prefer to use "exit(1)" instead of "return 1", since when we eventually write code outside of the main() block "exit(1)" will still exit the program, but "return 1" won't. The "exit" function is available from the "iostream" library, for example.

do-while loops

We've spent a lot of time with while-loops and for-loops. Both of these loops test whether to continue, and then go through the loop body, i.e. the test is done at the beginning of the loop. A "do-while" loop allows you to put the test at the end of the loop. This is convenient for certain tasks. For example, we looked at a program that reads expressions like:
1 + 5 + 3 + 48 + 32 =
and prints out the resulting sum. This can be done nicely with a do-while

#include <iostream>
using namespace std;

int main()
{
  int next, sum = 0;
  char op;




  do {
    cin >> next;
    sum = sum + next;
    cin >> op;
  } while(op != '=');

  return 0;
}

#include <iostream>
using namespace std;

int main()
{
  int next, sum = 0;
  char op;

  // Must initialize with something other than '=' 
  // just to make sure we enter the loop the first time.
  op = 'X';
  while(op != '=') {
    cin >> next;
    sum = sum + next;
    cin >> op;
  }

  return 0;
}

In case you don't find that compelling, here's another example. Suppose we want to keep reading in ints from a list until we read a negative number.


#include <iostream>
using namespace std;

int main()
{
  int n;


  do {
    cin >> n;
  }while(n >= 0);


  return 0;
}
#include <iostream>
using namespace std;

int main()
{
  int n;

  cin >> n;    // read n the first time...     
  while(n >= 0) 
  {
    cin >> n;
  }

  return 0;
}

switch statements

The switch statement is a bit of a holdover from the C language on which C++ is based, but it is something you'll probably see if you look at a lot of programs. You use a switch statement when you want to test a single variable or expression for several different cases. The hitch is that the variable pretty much needs to be an int or a char, which limits when switch can be used. Switch breaks things up into cases. You write
switch(expr)
{
... where expr is an expression of type int or char, and then list cases consisiting of possible values of expr. These cases must be constants, and each case is followed by a :, then a sequence of statements to be executed, and finally a break;. In other words, each case looks like this:
case constk:
         stmt1
         stmt2
         ...
         stmtr
break;
You can list as many of these cases as you want. You can also put
default:
         stmt1
         stmt2
         ...
         stmtr
break;
}
in as one "case". This is a catch-all that catches every situation in which expr didn't match one of the other cases. Here's an example program using switch. It reads a date in "mm/dd/yyyy" format and returns the date in "dd monthname, yyyy" format.

Practice Problems

  1. Write a program that draws a triangular tree, and the user provides the tree's height. A typical run of the program looks like the following:

    $ ./tree
    Enter height of tree: 10
              *
             ***
            *****
           *******
          *********
         ***********
        *************
       ***************
      *****************
     *******************
    
    The source code is given here.