Function Calling Functions
-
A function can call another function.
-
Not too surprising since the main function can call any other function.
-
In CS1124, we'll see that a function can even call itself.
-
The only restriction is that the prototype must appear before the function is used.
-
//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(firstNum, secondNum);
orderNumbers(firstNum, secondNum);
displayResults(firstNum, secondNum);
}
//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;
}