Make your own free website on Tripod.com

Tutorial 6

Program-Defined Value-Returning Functions

 The instructorís notes for this tutorial will consist of the following:

Overview

In Tutorial 5 the concepts of built-in functions (functions already defined and stored in a library) were covered. Tutorial 6 addresses the concept of the programmer writing his/her own functions in a program vs. calling already existing functions. More specifically this tutorial covers value-returning functions (void functions will be covered in the next tutorial). In order for the programmer to build their own functions, the concepts of a function prototype, understanding scopes of variables, and passing information (by value) to a function will also be covered.

Objectives

After completing the tutorial, the student will be able to:

 

Built-in vs. program-defined functions

A built-in function is a function whose task is predefined and whose code resides in a library file on your computerís hard disk. A program-defined function, on the other hand, is a function whose task is defined within the program itself. Programmers use program-defined functions for two reasons: program-defined functions allow the programmer to avoid duplicating code in different parts of the program, and they allow large and complex programs to be broken down into small and manageable tasks. Program-defined functions are called in exactly the same manner as you would call a built-in function (by including its name and actual arguments, if any, in a statement).

All built-in and program-defined functions are categorized as either value-returning functions or void functions. Value-returning functions return a value to the statement that called the function, whereas void functions do not return a value. Void functions will be covered in the next tutorial.

Defining a value-returning function

When defining a value-returning function you must code the function header and the function body. The function header is the first statement in the function definition. It specifies the type of data the function will return, the name of the function, and any optional parameters the function may have. The following is the syntax for a functions header: returnDataType functionName ( LEFTSQUAREparameterListRIGHTSQUARE ); . Note that the rules for naming functions are the same as the rules for naming variables.

You probably noted the term parameter in the syntax for the function header. When you were calling built-in functions, you were including the actual arguments in the parentheses after the function name (see tutorial 5 for review if necessary). Another term for the actual arguments could be actual parameters. When calling a built-in function you only needed to concern yourself with how many arguments (parameters) to pass to the function, because some other programmer has already defined the function. When this programmer defined the function, he/she defined it similar to the way we are now, and included a set of parameters (if any were needed) in his/her function header. These parameters correspond to the set of actual parameters when the function is called, and are called formal parameters.

When listing the actual parameters in the function call you need to only include the values (whether they are variables, named constants, literals, etc.) you wish to pass to the function, because these values have already been defined in the program. However when we are defining the function header, the formal parameters we are using (that match the actual parameters) have not yet been defined anywhere in the program. Therefore when listing them in the function header, we must also include their corresponding data type. This is coded similarly to declaring a variable where the data type is followed by the variable name (see page 190 for examples). If the function you are defining requires more than one formal parameter, then each formal parameterís data type and name are separated by a comma (see page 190 for an example). Note that some functions will not require parameters, in this case an empty set of parentheses is coded.

One very important item to note with the relationship between actual and formal parameters is that they must match in three ways: number, type, and order. In other words, if there are three formal parameters, there must also be three actual parameters. If the first formal parameter is of the type int, then the last two are of the type float, then the corresponding actual parameters must be the same corresponding types. Finally, the computer does not understand your problem and cannot match parameters for you. Therefore if you code as the first formal parameter an id code, followed by a salary and tax amount as the second and third, you must list your actual parameters in same exact order.

Another important item to note with the relationship between actual and formal parameters is naming them. If one person were writing an entire program, and had declared and passed a single variable called age through a function call to a function called displayAge, would it be possible to name the corresponding formal parameter age also? The answer would be yes. While many situations may not lend itself to this situation, it would be quite desirable if you were writing the entire program, because you would not have two different names for the same value. However, if you asked a colleague to write the displayAge function for you, more than likely the formal parameter name chosen would not be the same as your actual parameter name in the main function.

After coding the function header the function body must be coded. The function body will contain the instructions necessary for the function to accomplish its task. The function body will begin with an opening brace ( { ) and end with a closing brace ( } ). The last statement before the ending brace in the function body should be a return statement. The return statement will return a single value back to the statement that called the function. The syntax of the return statement is: return expression; , where expression is the value the function returns to the statement that called it. Note that type data type of the expression must agree with the return data type of the function.

Calling a program-defined function

As stated previously, you call a program-defined function the same way you call a built-in function. When the computer processes a statement containing a program-defined function, the computer first locates the functionís code in the program. In C++ the code for all program-defined functions is usually placed after the main function. Remember from the previous discussion that if the program-defined function has any parameters (formal parameters), then the actual parameters included in the function call must match in three ways: number, type, and order.

Since in C++ you may not use functions until they are defined (built-in functions are defined when you issue the #include directive for the library containing the function), we must somehow define the program-defined function before the main function calls it. This is accomplished by placing a function prototype in the program. Function prototypes are usually placed at the beginning of the program, after the #include directives.

Function prototypes

You declare a program-defined function by using a function prototype. The function prototype contains the data type of the return value of the function, the name of the function, and the data type of each of the formal parameters. The function prototype is usually placed at the beginning of the program, after the #include directives, but before the beginning of the main function.

The function prototype alerts the compiler that the function will be defined in its entirety later in the program, however satisfies the rule that a function must be declared before it is called. This way the compiler knows the basic information about a function (number of parameters, their types, name of the function, etc.), so when a function call is made it may have some information to compare to.

Note that the function prototype ends with a semicolon where the function header does not end with a semicolon.

Passing parameters by value

You learned previously that the actual parameters that can be passed to a functionís corresponding formal parameters can be one or more variables, named constants, literal constants, or keywords. When the actual parameter is a variable, the variable can either be passed by value or passed by reference. When a variable is passed by value, only the value stored in the variable is passed to the function. When a variable is passed by reference, the address of the variable in memory is passed. Unless otherwise specified, C++ automatically passes variables by value. Passing variables by reference will be covered in a later tutorial.

 

Scope and lifetime of variables

A variableís scope, which can be either local or global, indicates which portions of a program can use the variable. A variableís lifetime, on the other hand, indicates how long the variable will remain in memory. Local variables can be used only by the function in which they are declared, and they remain in memory until the function ends. (As you will learn in future tutorials, variables declared in a statement block in a C++ program are local to that statement block, and they remain in memory until the statement block ends.) Global variables, which you should avoid using, can be used anywhere in the program, and they remain in memory until the program ends.

By only allowing a function to utilize local variables declared within it, or parameters passed to it, the function becomes very portable. In other words, the function stands alone and could be included in a library to be used in other programs. However once a function is allowed to utilize a global variable, without having the same global variable (with the same meaning, data type, etc.) in a program you wish to use the function, many modifications may have to be made to the new program to accommodate the function, therefore eliminating portability.

 

Solutions to Questions

1. b program-defined value-returning

2. a one value only

3. d all of the above

4. c The name of each actual argument should be identical to the name of its corresponding

formal parameter

5. d a formal parameter

6. b }

7. c float calcTax (float salesAmount)

8. d float fee (int base, float rate)

9. d None of the above

10. d by value

11. b it removes the functionís local variables (if any) from memory, then continues program

execution with the statement that called the function

12. c scope

13. a The beginBalance variable will remain in memory until the compiler encounters the functionís

return statement

14. a store the result in the displayGross functionís pay variable

Solutions to Concept Lesson Exercises

Answers to exercises 1 through 6 may vary.

  1. float halveNumber(int num)
  2. {

    return num / 2;

    } //end of halveNumber function

     

  3. char getChar()
  4. {

    char character = Ď í;

    cout << "Enter a character: ";

    cin >> character;

    return character;

    } //end of getChar function

     

  5. float calcAverage(int N1, int N2, int N3, int N4)
  6. {

    return (N1 + N2 + N3 + N4) / 4;

    } //end of calcAverage function

     

  7. float quotient(float N1, float N2)
  8. {

    return N1 / N2;

    } //end of quotient function

     

  9. string getName()
  10. {

    string name = "";

    cout << "Enter a name: ";

    getline(cin, name);

    return name;

    } //end of getName function

     

  11. int getRandomNumber(int lowNum, int upperNum)
  12. {

    return lowNum + rand() % (upperNum Ė lowNum + 1);

    } //end of getRandomNumber function

  13. Desk-check table after the first four instructions in the main function are processed:
  14.  


    begVal

    purchase

    sale

    endVal

    1000

    500

    200

    0

     

    Desk-check table after the calcEnd functionís return statement is processed (but before local variables are removed from memory):

     



    begVal

    purchase

    sale

    endVal

     

    b

    p

    sale

    endValue

    1000

    500

    200

    0

    1300

    1000

    500

    200

    0

    1300

    Desk-check table after the calcEnd functionís local variables are removed from memory:

     


    begVal

    purchase

    sale

    endVal

    1000

    500

    200

    0

    1300

     

  15. //T6ConE08.cpp - doubles the number entered by the user, then displays the result

    #include <iostream>

    using namespace std;

    //function prototype (you will learn about function prototypes in the Application lesson)

    int calcDoubleNumber();

    //declare global variable

    int number = 0;

    int main()

    {

    //declare variables

    //int number = 0;

    int doubleNumber = 0;

    //get input item

    cout << "Enter a number: ";

    cin >> number;

    //double the number

    doubleNumber = calcDoubleNumber();

    //display result

    cout << "Answer: " << doubleNumber;

    return 0;

    } //end of main function

    //*****program-defined functions*****

    int calcDoubleNumber()

    {

    return number * 2;

    } //end of calcDoubleNumber function

  16.  
  17.  

  18. The corrected function header is float calcCommission(string name, float sales, float rate).

  

Solutions to Application Lesson Exercises

 

  1. It is better to finance the car through the car dealer.
  2. //T6AppE01.cpp - displays monthly payments

    #include <iostream>

    #include <cmath>

    using namespace std;

    //function prototype

    float calcPayment(int, float, int);

    int main()

    {

    int carPrice = 0;

    int rebate = 0;

    float creditRate = 0.0;

    float dealerRate = 0.0;

    int term = 0;

    float mthCreditRate = 0.0;

    float mthDealerRate = 0.0;

    int numMonths = 0;

    float creditPay = 0.0;

    float dealerPay = 0.0;

    //enter input items

    cout << "Enter the car price: ";

    cin >> carPrice;

    cout << "Enter the rebate: ";

    cin >> rebate;

    cout << "Enter the credit union rate: ";

    cin >> creditRate;

    cout << "Enter the dealer rate: ";

    cin >> dealerRate;

    cout << "Enter the term (years): ";

    cin >> term;

    //convert annual rates and term to monthly

    mthCreditRate = creditRate /12;

    mthDealerRate = dealerRate /12;

    numMonths = term * 12;

    //calculate monthly payments

    creditPay = calcPayment(carPrice - rebate, mthCreditRate, numMonths);

    dealerPay = calcPayment(carPrice, mthDealerRate, numMonths);

    //display monthly payments

    cout << fixed;

    cout.precision(2);

    cout << "Credit union payment: " << creditPay << endl;

    cout << "Dealer payment: " << dealerPay << endl;

    return 0;

    } //end of main function

     

     

     

    //*****program-defined functions*****

    float calcPayment(int prin, float monthRate, int months)

    {

    //calculates and returns a monthly payment

    float monthPay = 0.0;

    monthPay = prin * monthRate / (1 - pow(monthRate + 1, -months));

    return monthPay;

    } //end of calcPayment function

     

  3. It is better to finance the car through the credit union.

//T6AppE02.cpp - displays monthly payments

#include <iostream>

#include <cmath>

using namespace std;

//function prototype

float calcPayment(int, float, int);

int main()

{

int carPrice = 0;

int rebate = 0;

float creditRate = 0.0;

float dealerRate = 0.0;

int term = 0;

float creditPay = 0.0;

float dealerPay = 0.0;

//enter input items

cout << "Enter the car price: ";

cin >> carPrice;

cout << "Enter the rebate: ";

cin >> rebate;

cout << "Enter the credit union rate: ";

cin >> creditRate;

cout << "Enter the dealer rate: ";

cin >> dealerRate;

cout << "Enter the term (years): ";

cin >> term;

//convert annual rates and term to monthly

creditRate = creditRate /12;

dealerRate = dealerRate /12;

term = term * 12;

//calculate monthly payments

creditPay = calcPayment(carPrice - rebate, creditRate, term);

dealerPay = calcPayment(carPrice, dealerRate, term);

//display monthly payments

cout << "Credit union payment: " << creditPay << endl;

cout << "Dealer payment: " << dealerPay << endl;

return 0;

} //end of main function

//*****program-defined functions*****

float calcPayment(int prin, float monthRate, int months)

{

//calculates and returns a monthly payment

float monthPay = 0.0;

monthPay = prin * monthRate / (1 - pow(monthRate + 1, -months));

return monthPay;

} //end of calcPayment function

 

 

3.

fahrenheit

celsius

tempF

tempC

0

32

0

212

0.0

0.0

0.0

100.0

0

32

0

212

0.0

0.0

0.0

100.0

//T6AppE03.cpp - displays a Celsius temperature

#include <iostream>

using namespace std;

//function prototypes

int getFahrenheit();

float calcCelsius(int);

int main()

{

//declare variables

int fahrenheit = 0;

float celsius = 0.0;

//get input item

fahrenheit = getFahrenheit();

//calculate Celsius

celsius = calcCelsius(fahrenheit);

//display output item

cout << fixed;

cout.precision(0);

cout << "Celsius: " << celsius << endl;

return 0;

} //end of main function

//*****program-defined functions*****

int getFahrenheit()

{

int tempF = 0;

cout << "Enter Fahrenheit temperature: ";

cin >> tempF;

return tempF;

} //end of getFahrenheit function

float calcCelsius(int tempFahrenheit)

{

float tempC = 0.0;

tempC = 5.0 / 9.0 * (tempFahrenheit - 32);

return tempC;

} //end of calcCelsius function

4.

sales

bonus

saleAmt

bonusAmt

0.0

24500.0

0.0

134780

0.0

2450.0

0.0

13478.0

0.0

24500.0

0.0

134780

0.0

2450.0

0.0

13478.0

//T6AppE04.cpp - displays a bonus

#include <iostream>

using namespace std;

//function prototypes

float getSales();

float calcBonus(float);

int main()

{

//declare variables

float sales = 0.0;

float bonus = 0.0;

//get input item

sales = getSales();

//calculate bonus

bonus = calcBonus(sales);

//display output item

cout << fixed;

cout.precision(2);

cout << "Bonus: " << bonus << endl;

return 0;

} //end of main function

//*****program-defined functions*****

float getSales()

{

float saleAmt = 0.0;

cout << "Enter a sales amount: ";

cin >> saleAmt;

return saleAmt;

} //end of getSales function

float calcBonus(float dollars)

{

float bonusAmt = 0.0;

bonusAmt = dollars * .1;

return bonusAmt;

} //end of calcBonus function

 

5.

//T6AppE05.cpp - displays the present value of a series of periodic payments

#include <iostream>

#include <cmath>

#include <fstream>

using namespace std;

//function prototypes

float getRate();

float calcPrin(int, int, float);

int main()

{

const int PAYMENT = 360;

const int TERM = 48;

float rate = 0.0;

float principal = 0.0;

ofstream outFile;

outFile.open("T6AppE05.dat");

//enter input item

rate = getRate();

//calculate present value (principal)

principal = calcPrin(PAYMENT, TERM, rate);

//display output items

cout << fixed;

cout.precision(0);

cout << "You can borrow up to $" << principal << endl;

outFile << fixed;

outFile.precision(0);

outFile << "You can borrow up to $" << principal << endl;

outFile.close();

return 0;

} //end of main function

//*****program-defined functions*****

float getRate()

{

float intRate = 0.0;

cout << "Enter the annual interest rate: ";

cin >> intRate;

return intRate / 12;

} //end of getRate function

float calcPrin(int monthPay, int months, float intRate)

{

return monthPay * (1 - pow(intRate + 1, -months)) / intRate;

} //end of calcPrin function

 

Contents of the T6AppE05.dat file

You can borrow up to $15034

6.

main function

Input

Processing

Output

score 1

score 2

score 3

Processing items: None

Algorithm:

  1. score 1 = getTestScore()
  2. score 2 = getTestScore()
  3. score 3 = getTestScore()
  4. average = calcAverage(score 1, score 2, score 3)
  5. display the average

average

getTestScore function

Input

Processing

Output

 

Processing items: None

Algorithm:

  1. enter the score
  2. return the score

score

calcAverage function

Input

Processing

Output

score 1

score 2

score 3

 

Processing items: None

Algorithm:

  1. calculate average by adding together score 1, score 2, and score 3, and then dividing the sum by 3
  2. return the average

average

score1

score2

score3

avg

testScore

average

0.0

95.5

0.0

54

0.0

83

0.0

89

0.0

76

0.0

77

0.0

84.8

0.0

73.3

0.0

95.5

0.0

83

0.0

76

0.0

54

0.0

89

0.0

77

0.0

84.8

0.0

73.3

//T6AppE06.cpp - displays the average

#include <iostream>

using namespace std;

//function prototypes

float getTestScore();

float calcAverage(float, float, float);

int main()

{

float score1 = 0.0;

float score2 = 0.0;

float score3 = 0.0;

float avg = 0.0;

//enter input items

score1 = getTestScore();

score2 = getTestScore();

score3 = getTestScore();

//calculate average

avg = calcAverage(score1, score2, score3);

//display output item

cout << fixed;

cout.precision(1);

cout << "Average: " << avg << endl;

return 0;

} //end of main function

//*****program-defined functions*****

float getTestScore()

{

float testScore = 0.0;

cout << "Enter the test score: ";

cin >> testScore;

return testScore;

} //end of getTestScore function

float calcAverage(float test1, float test2, float test3)

{

float average = 0.0;

average = (test1 + test2 + test3) / 3;

return average;

} //end of calcAverage function

 7.

main function

Input

Processing

Output

name

hours

pay rate

 

Processing items: None

Algorithm:

  1. name = getName()
  2. hours = getHoursWorked()
  3. pay rate = getPayRate()
  4. gross = calcGross(name, hours, pay rate)
  5. display the name and gross

name

gross

getName function

Input

Processing

Output

 

Processing items: None

Algorithm:

  1. enter the name
  2. return the name

name

getHoursWorked function

Input

Processing

Output

 

 

Processing items: None

Algorithm:

  1. enter the hours
  2. return the hours

hours

getPayRate function

Input

Processing

Output

 

Processing items: None

Algorithm:

  1. enter the pay rate
  2. return the pay rate

pay rate

calcGross function

Input

Processing

Output

hours

pay rate

 

Processing items: None

Algorithm:

  1. calculate gross by multiplying hours by pay rate
  2. return the gross

gross

 

name

hours

rate

gross

employee

hoursWkd

payRate

grossPay

Mary Smith

Jack Vitor

0.0

25.5

0.0

40

0.0

12

0.0

11.55

0.0

306.0

0.0

462.0

Mary Smith

Jack Vitor

0.0

25.5

0.0

40

0.0

12

0.0

11.55

0.0

306.0

0.0

462.0

//T6AppE07.cpp - displays the gross pay

#include <iostream>

#include <string>

using namespace std;

//function prototypes

string getName();

float getHoursWorked();

float getPayRate();

float calcGross(float, float);

int main()

{

string name = "";

float hours = 0.0;

float rate = 0.0;

float gross = 0.0;

//enter input items

name = getName();

hours = getHoursWorked();

rate = getPayRate();

//calculate gross

gross = calcGross(hours, rate);

//display output item

cout << fixed;

cout.precision(2);

cout << "Gross pay: " << gross << endl;

return 0;

} //end of main function

//*****program-defined functions*****

string getName()

{

string employee = "";

cout << "Enter the name: ";

getline(cin, employee);

return employee;

} //end of getName function

float getHoursWorked()

{

float hoursWkd = 0.0;

cout << "Enter the hours worked: ";

cin >> hoursWkd;

return hoursWkd;

} //end of getHoursWorked function

float getPayRate()

{

float payRate = 0.0;

cout << "Enter the hourly pay rate: ";

cin >> payRate;

return payRate;

} //end of getPayRate function

float calcGross(float numHours, float hourPay)

{

float grossPay = 0.0;

grossPay = numHours * hourPay;

return grossPay;

} //end of calcGross function

8. It is better to finance the car through the car dealer.

//T6AppE08.cpp - displays monthly payments

#include <iostream>

#include <cmath>

using namespace std;

//function prototype

float calcPayment(int, float, int);

void displayPayment(float);

int main()

{

int carPrice = 0;

int rebate = 0;

float creditRate = 0.0;

float dealerRate = 0.0;

int term = 0;

float mthCreditRate = 0.0;

float mthDealerRate = 0.0;

int numMonths = 0;

float creditPay = 0.0;

float dealerPay = 0.0;

//enter input items

cout << "Enter the car price: ";

cin >> carPrice;

cout << "Enter the rebate: ";

cin >> rebate;

cout << "Enter the credit union rate: ";

cin >> creditRate;

cout << "Enter the dealer rate: ";

cin >> dealerRate;

cout << "Enter the term (years): ";

cin >> term;

//convert annual rates and term to monthly

mthCreditRate = creditRate /12;

mthDealerRate = dealerRate /12;

numMonths = term * 12;

//calculate monthly payments

creditPay = calcPayment(carPrice - rebate, mthCreditRate, numMonths);

dealerPay = calcPayment(carPrice, mthDealerRate, numMonths);

//display monthly payments

cout << "Credit union payment: ";

displayPayment(creditPay);

cout << "Dealer payment: ";

displayPayment(dealerPay);

return 0;

} //end of main function

 

 

 

 

 

 

//*****program-defined functions*****

float calcPayment(int prin, float monthRate, int months)

{

//calculates and returns a monthly payment

float monthPay = 0.0;

monthPay = prin * monthRate / (1 - pow(monthRate + 1, -months));

return monthPay;

} //end of calcPayment function

void displayPayment(float monthPay)

{

cout << monthPay << endl;

} //end of displayPayment function

 9. Changes made to the original code are shaded.

//T6AppE09.cpp - displays the miles per gallon

#include <iostream>

using namespace std;

//function prototypes

float getMiles();

float getNumGallons();

float calcMpg(float, float);

int main()

{

float miles = 0.0;

float gallons = 0.0;

float milesPerGal = 0.0;

//enter input items

miles = getMiles();

gallons = getNumGallons();

//calculate miles per gallon

milesPerGal = calcMpg(miles, gallons);

//display output item

cout << fixed;

cout.precision(1);

cout << "Miles per gallon: " << milesPerGal << endl;

return 0;

} //end of main function

//*****program-defined functions*****

float getMiles()

{

float numMiles = 0.0;

cout << "Enter the number of miles: ";

cin >> numMiles;

return numMiles;

} //end of getMiles function

float getNumGallons()

{

float numGallons = 0.0;

cout << "Enter number of gallons: ";

cin >> numGallons;

return numGallons;

} //end of getNumGallons function

float calcMpg(float distance, float galUsed)

{

return distance / galUsed;

} //end of calcMpg function

 10. Changes made to the original code are shaded.

/T6AppE10.cpp - displays the product of two numbers

#include <iostream>

using namespace std;

//function prototype

float calcProduct(float, float);

int main()

{

//declare variables

float num1 = 0.0;

float num2 = 0.0;

float product = 0.0;

//enter input items

cout << "Enter the first number: ";

cin >> num1;

cout << "Enter the second number: ";

cin >> num2;

//calculate product

product = calcProduct(num1, num2);

//display output items

cout << "The product of " << num1 << " and " << num2;

cout << " is " << product << endl;

return 0;

} //end of main function

 

//*****program-defined functions*****

float calcProduct(float num1, float num2)

{

return num1 * num2;

} //end of calcProduct function

 11. Changes made to the original code are shaded.

/T6AppE11.cpp - displays the product of two numbers

#include <iostream>

using namespace std;

//function prototype

float calcProduct(float, float);

int main()

{

//declare variables

float num1 = 0.0;

float num2 = 0.0;

float product = 0.0;

//enter input items

cout << "Enter the first number: ";

cin >> num1;

cout << "Enter the second number: ";

cin >> num2;

//calculate product

product = calcProduct(num1, num2);

//display output items

cout << "The product of " << num1 << " and " << num2;

cout << " is " << product << endl;

return 0;

} //end of main function

 

//*****program-defined functions*****

float calcProduct(float num1, float num2)

{

return num1 * num2;

} //end of calcProduct function