Function Calling Functions

  1. A function can call another function.

  2. Not too surprising since the main function can call any other function.

  3. In CS1124, we'll see that a function can even call itself.

  4. The only restriction is that the prototype must appear before the function is used.

  5. //Program to illustrate a function calling another function.
    //The user enters 2 integers from the keyboard.
    //The program displays the numbers in increasing order.

    #include<iostream>
    using namespace std;

    void getInput(int& input1, int& input2);
    //Reads two integers from the keyboard.

    void swapValues(int& variable1, int& variable2);
    //Interchanges the values of variable1 and variable2.

    void orderNumbers(int& n1, int& n2);
    //Orders the numbers in the variables n1 and n2
    //so that n1 <= n2.

    void displayResults(int output1, int output2);
    //Outputs the values in output1 and output2.
    //Assumes that output1 <= output2


    int main( )
    {
          int firstNum, secondNum;

          getInput(first_num, second_num);
          orderNumbers(first_num, second_num);
          displayResults(first_num, second_num);
          return 0;
    }


    //Uses iostream:
    void getInput(int& input1, int& input2)
    {
          cout << "Enter two integers: ";
          cin >> input1 >> input2;
    }

    void swapValues(int& variable1, int& variable2)
    {
          int temp;

          temp = variable1;
          variable1 = variable2;
          variable2 = temp;
    }

    void orderNumbers(int& n1, int& n2)
    {
          if (n1 > n2)
          swapValues(n1, n2);
    }

    //Uses iostream:
    void displayResults(int output1, int output2)
    {
          cout << "In increasing order the numbers are: "
                << output1 << " " << output2 << endl;
    }