A Recursion Excursion

When you are done with assignment number three you should continue on with this brief exploration of recursion. This is the technique that I mentioned where you could have one function call itself to allow for a menu to be called as many times as you wanted until the user selects quit. It also has a lot of other uses in programming, one of which you will learn about in the book. When you are done with this brief online exercise you should read pages 158-161 in A Computer Science Tapestry.

Below is a program which simply calls a menu as many times as a user wants until they select the quit option.

#include <iostream.h>
int menu(void)
{
    int selection;
    cout<<"Choose a selection from the following menu:"<<endl;
    cout<<"1. Continue"<<endl;
    cout<<"2. Quit"<<endl;
    cout<<"Enter your selection: ";
    cin>>selection;
    if(selection==1)
    {
        menu();
    }
    else if(selection==2)
    {
        return 0;
    }
    else
    {
        cout<<"That is not a valid selection"<<endl;
        menu();
    }
    return 0;
}
 
int main(void)
{
    menu();
    return 0;
}

Note that the menu function calls the menu function itself. If the user selects to continue many times in a row, they will be many layers deep in menu functions. When the user finally selects option number 2 (quit) the first of these will return 0 (exit) through the if statement. Each of the other menu functions that have been called will in turn return 0 because they will get to the last line of code. I will illustrate this in class.

Try out the above program and try to implement one of the previous menus (from assignment 2 or 3) in this way. Then read the section from the book about recursion and exponentiation.

Back to Home Page House3.wmf (25540 bytes)