< Previous | Contents | Next >

Introducing the Give Me a Number Program

The Give Me a Number program asks the user for two different numbers in two different ranges. The same function is called each time the user is prompted for a number. However, each call to this function uses a different number of arguments because this function has a default argument for the lower limit. This means the caller can omit an argument for the lower limit, and the function will use a default value automatically. Figure 5.5 shows the results of the program.


image

Figure 5.5

A default argument is used for the lower limit the first time the user is prompted for a number.

172 Chapter 5 n Functions: Mad Lib


You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 5 folder; the filename is give_me_a_number.cpp.


// Give Me a Number

// Demonstrates default function arguments


#include <iostream> #include <string>


using namespace std;

int askNumber(int high, int low = 1); int main()

{

int number = askNumber(5);

cout << "Thanks for entering: " << number << "\n\n";


number = askNumber(10, 5);

cout << "Thanks for entering: " << number << "\n\n";


return 0;

}


int askNumber(int high, int low)

{

int num; do

{

cout << "Please enter a number" << " (" << low << " - " << high << "): "; cin >> num;

} while (num > high || num < low);


return num;

}

Using Default Arguments 173