Chapter 1
Introduction

Chapter 2
Functions

Chapter 3
Branching

Chapter 4
Iteration

Chapter 5
OOP

Chapter 6
Arrays


CHAPTER 2

( Functions )

1 )
Functions

2 ) More On Functions

When we build a house why do we make rooms? In our daily life why do we use so many different people who specialize in different professions, such as physicians, lawyers, accountants, etc? Same reasoning can be applied to programming. When we write a good program, it must be divided into modules; each module is designed to do a particular task. In C++ there are two types of modules, functions and classes. In this chapter we will deal with functions. You can write functions that can be used over and over again in a program or in several programs. In fact, the C++ standard library comes with many functions for mathematical, string, and character manipulations.

A large programming job needs to be broken down to manageable smaller modules; this breaking down process is called top down design. Here is one of my favorite hymns written using functions. I have broken down the hymn into five functions, four verses and one chorus. The main function simply calls the other functions. Even though the program is given in two text boxes for clarity, please combine them into one program.

Program 2-1

/*****************************

Program: Function Calls

Written by: Dr. John P. Abraham

Instructional objective: Functions

*****************************/

#include <iostream.h>

void chorus();

void verse1();

void verse2();

void verse3();

void verse4();

void verse5();

int main()

{

verse1();

chorus();

verse2();

chorus();

verse3();

chorus();

verse4();

chorus();

verse5();

chorus();

return(0);

}

 

Program 2-1 continued:

void chorus()

{

cout<< "Hosts of angels anxiously ready and waiting\n";

cout<< "They stand ready to bid me welcome\n";

cout<< "All my robes made so gleaming bright\n";

cout<< "I will sing Hallelujah at His sight\n\n";

}

void verse1()

{

cout<< "I ran my race on this earth\n";

cout<< "Stand ready for the price before me\n";

cout<< "Transfigured I will fly home, heavenly home\n";

cout<< "To stand in the presence of my Lord\\n\n";

}

void verse2()

{

cout << "For years I hoped and longed\n";

cout << "To see my King face to face\n";

cout << "Soon I will behold him in Glory\n" ;

cout << "I'll rest in His embracing arms\n\n";

}

void verse3()

{

cout << "I long toiled and labored\n";

cout << "For my Master; now He honors me\n";

cout << "With accolades and showers of\n";

cout << "Gifts to decorate my crown\n\n";

}

void verse4()

{

cout << "His saints and righteous servants\n";

cout << "Those who gave their life for The Lord\n";

cout << "As they play their strings to the Lord\n";

cout << "I will sing and join that crowd\n\n";

}

void verse5()

{

cout << "In the mansion made not by hand\n";

cout << "In the city of new Jerusalem\n";

cout << "Evermore as a bride in hand\n";

cout << "I'll reign with my savior dear\n\n";

}

Program Run 2-1

I ran my race on this earth

Stand ready for the price before me

Transfigured I will fly home, heavenly home

To stand in the presence of my Lord

Hosts of angels anxiously ready and waiting

They stand ready to bid me welcome

All my robes made so gleaming bright

I will sing Hallelujah at His sight

For years I hoped and longed

To see my King face to face

Soon I will behold him in Glory

I'll rest in His embracing arms

Hosts of angels anxiously ready and waiting

They stand ready to bid me welcome

All my robes made so gleaming bright

I will sing Hallelujah at His sight

I long toiled and labored

For my Master; now He honors me

With accolades and showers of

Gifts to decorate my crown

Hosts of angels anxiously ready and waiting

They stand ready to bid me welcome

All my robes made so gleaming bright

I will sing Hallelujah at His sight

His saints and righteous servants

Those who gave their life for The Lord

As they play their strings to the Lord

I will sing and join that crowd

Hosts of angels anxiously ready and waiting

They stand ready to bid me welcome

All my robes made so gleaming bright

I will sing Hallelujah at His sight

In the mansion made not by hand

In the city of new Jerusalem

Evermore as a bride in hand

I'll reign with my savior dear

Hosts of angels anxiously ready and waiting

They stand ready to bid me welcome

All my robes made so gleaming bright

I will sing Hallelujah at His sight

When we run this program, the hymn is displayed verse1, chorus, verse2, chorus, and so on. Look at the main, it is not cluttered. In the main, the functions were called. The function chorus was called four times; all other functions were called only once. The main function returned a zero to the operating system indicating all is well; all other procedures returned nothing. Before calling the functions, the prototypes of the functions must be declared. Please underline the prototypes just above the main in order for you to remember to do it when you write your programs. The function prototype contains the following information: (1) name of the function, (2) the type of data returned by the function, and (3) number, type, and order of parameters passed into the function. Let us write another program to find centigrade given Fahrenheit.

Program 2-2

/***************************************

Program: Function Calls

Written by: Dr. John P. Abraham

Instructional objective: Passing Parameters

**************************************/

 

#include <iostream.h>

float celsius(float);

int main ()

{

float c, f; //Centigrade and Fahrenheit

cout << "Enter today's temperature in degrees of Fahrenheit ";

cin >> f;

c = celsius(f);

cout << "That equals " << c << " degrees of celsius!\n" ;

return(0);

cout << "Press the Enter key to stop the Program!";

getchar();

}

float celsius (float f)

{

return ((f-32)*5/9);

}

Program Run 2-2

Enter today's temperature in degrees of fahrenheit 92

That equals 33.3333 degrees of celcius!

 

The function prototype is given immediately after the include statement. The prototype indicates that the function-celsius will receive one float parameter and will return one float value back. In the main variable c is assigned the result of the function-celsius. It is very important that you understand this concept of passing parameters and returning results. Please type this program in as many times as required until you can do it without referring to the notes.

Next we need to concentrate on the scope of variables. This world has lots of people called John. So when someone calls John, which John should answer? In a program, you may use the same identifier name in different functions. There needs to be some rules about the scope of the variables. The scope of variables concept is very important, please pay attention to every sentence in the following few paragraphs. When a parameter is passed in, as in the example in program 2-2, the contents of that memory location (referred to as f in this example) is sent to the called function (function-celsius). This variable exists in that function only during the execution of that function. If that function is called again, the old value is gone and whatever is passed is placed there. Run the following program to understand this concept.

Program 2-3

/*****************************

Program: Function Calls

Written by: Dr. John P. Abraham

Instructional objective: Scope of variables

*****************************/

#include <iostream.h>

void changex (int);

int main ()

{

int x;

x = 5;

cout << "In the main, value of x before the first call ----> " << x <<"\n";

changex(x);

cout << "In the main, value of x after the first call -----> " << x <<"\n";

x = 1;

cout << "In the main, value of x before the second call ----> " << x <<"\n";

changex(x);

cout << "In the main, value of x after the second call -----> " << x <<"\n";

return (0);

}

void changex (int x)

{

cout << " in the function, value of x as it came in----> " << x << "\n";

x = x+10;

cout << " in the function, value of x after adding 10---> " << x << "\n";

}

 

When running this program please notice that x is first assigned value of 5 and this value is passed into the function as a copy (now x has a copy). The x is changed in the function to 15 by adding a 10. However after the function is executed, everything in the function including the x in the function, is erased. The original x in the main still has the value of 5. There is a way to keep the values of variables in a function. This is done by declaring the variables as static. This will not be discussed further here.

When a function is called and copies of the parameters are passed in as discussed in the previous paragraph, it is known as call-by-value. Another way to pass a parameter is to call-by-reference. When a parameter is passed call-by-reference the address of the original memory location is passed to the function. The function may change the contents of that memory location. The advantage here is that by not duplicating large blocks of data, memory can be saved. A disadvantage is accidentally changing (side effect) the value of a variable.

Now let us study the concept of global variables. A variable that is visible to a lower level module is called a global variable. In the program 2-4, x is declared as a global variable. This variable is visible by all modules and any module can change its value.

Program 2-4

/*****************************************

Program: Function Calls

Written by: Dr. John P. Abraham

Instructional objective: Global variables

******************************************/

#include <iostream.h>

int x;

void getvalue ();

int main ()

{

x = 1;

getvalue();

cout << "x contains a value of " << x <<"\n";

return(0);

}

void getvalue()

{

cout << "enter a value for x ";

cin >> x;

}

Program Run 2-4

enter a value for x 8

x contains a value of 8

Whatever you entered for the x in the function was displayed in the main; the function placed a value in x and the main was able to access that value. You can see the problems global variables can cause if you are not extremely careful. Therefore, use of global variables should be avoided unless you are a seasoned programmer.

It is time for us to examine the concept of local variables. Suppose a global variable x exists, and you declared another x in a function, and now you want to assign a value to x. Which x should get the value? Let us modify program 2-4 to include a local variable.

Program 2-5

/*****************************

Program: Function Calls

Written by: Dr. John P. Abraham

Instructional objective: local variables

*****************************/

#include <iostream.h>

int x;

void getvalue ();

int main ()

{

x =1;

getvalue();

cout << "x contains a value of " << x <<"\n";

return(0);

}

void getvalue()

{

int x;

cout << "enter a value for x ";

cin >> x;

}

Program Run 2-5

enter a value for x 15

x contains a value of 1

The x in the function getvalue is a local variable. Now you have an x global and an x local. When you assign a value to x, the local gets it and the global is not changed. The global was assigned a value of 1 in the main and the program displays a one.

Let us write a program to illustrate call-by-reference mentioned earlier. When a parameter is passed call-by-reference, any changes made to that variable in the function actually is changing the original variable. In the following example (Program 2-6), length and width are passed by reference. In order to pass by reference we use an ampersand & in front of the variable name. Note how the prototype is declared; here also we use an ampersand. Another interesting feature of functions is that you do not have to use the same identifier in the called and calling modules. For example, in the calling module the identifiers were length and width; in the called module the identifiers were l and w. The names do not have to match, but their order has to.

Program 2-6

/********************************

Program to Find square feet

Instructional objective: Passed-by-reference.

By Dr. John Abraham

Created for 1380 students

********************************/

 

#include <iostream.h>

 

void getmeasurements (int &, int &);

float calc_sqyards(int, int);

int main()

{

int length, width;

float sqyards;

getmeasurements(length, width);

sqyards = calc_sqyards(length, width);

cout << "The area in square yards is " << sqyards;

return (0);

}

void getmeasurements(int &l, int &w)

{

cout << "Enter length of the room in feet ";

cin >> l;

cout << "Enter width of the room in feet ";

cin >> w;

}

float calc_sqyards (int length, int width)

{

float area;

area = length * width/9;

return(area);

}

Program Run 2-6

Enter length of the room in feet 18

Enter width of the room in feet 15

The area in square yards is 30

By now you should have completed the assignment from Chapter 1; the program to printout how many thousands, hundreds, tens and ones in a given number. Let us continue working with that assignment. Change the program to incorporate some functions in that program. Here is the link to revised program: numbers.html. If this program does not come up, I may have removed it from the directory. Another version of the program also shows the outfiles: numbers1.html

Assignment

Write a program to accept the length and width of a room in feet and price per yard for carpet. Find the area of the room in square yards and calculate the cost of the carpet for the room.  Calculate sales Tax and print out a bid as shown below:

Enter length of the room ----------> 25
Enter width of the room -----------> 18
Enter price of carpet per yard --- > 21.45
C++ CARPET SALES AND INSTALLATION
address and telephone

Length of the room -------- > 25
Width of the room---------- > 18
Sq Yards of carpet needed---> 50
Cost of carpet ---> $1072.5
Sales Tax --------> $88.4813
                             --------------
Total-------------> $1160.98
Press any key to continue

More On Functions :

In this chapter we will review functions, follow an example program from planning to completion, and learn two new concepts, namely inline functions and function overloading. A function is a subprogram that specializes in doing one specific task. A function by definition may receive none, one, or many input parameters and output none or one parameter.

None or One output argument ß | Function | ß None, one or many input argument(s)

float findAverage (int grade1, int grade2, int grade3)

In this example the function findAverage receives 3 input arguments and returns one argument. The input arguments here are passed by value, meaning only copies of the three original variables appearing in the calling function are passed to the function. Even if the values of these variables are changed by the function, the original variables will remain unchanged. If a function does not return any result back just indicate so by stating void, example: void print (int grade1, int grade2, int grade3, float average).

Remember that the function only exists during its execution. Upon return from the function nothing remains of the function. A function is made upon calling it and destroyed upon returning. In order to call the above function, we can write the following statement:

average = findAverage(grade1, grade2, grade3);

Since we know that this function returns a float we must put this returned value somewhere; here we receive the result into average. We could have displayed the result directly on the screen by the statement:

cout << findAverage(grade1, grade2, grade3);

It is often necessary to use functions to read multiple variables and return them to the calling module. Based on the above definition it is impossible to send back more than one value. Here is where argument passing by reference comes in handy. Instead of returning the result, the function writes directly to the original memory locations of the reference variables. In the following is example, even though nothing is returned by the function, the calling function's three variables were changed with the read values.

void getGrades (int &grade1, int &grade2, int &grade3)

Suppose we want to write a program to find the average of three grades. We can generate a structure chart with three modules, getGrades, findAverage, and print. The Module getGrades receives three arguments by reference and returns none. The findAverage module receives one argument by value and returns a float. The last module receives four arguments by value and returns none. Draw a structure chart using these directions. The next step is to develop the prototypes. Translating a properly designed structure chart to prototypes is rather easy. The prototype for these three functions would be:

void getGrades (int&, int&, int&);

float findAverage (int, int, int);

void print (int, int, int, float);

Finally, let us write the whole program. The main should only declare variables that it uses. Do not declare variable a function might use as local variables. Convert the prototypes to functions and function calls.

/*************************************

Program to find average of 3 grades

objective: Review functions

Program by Dr. Abraham

**************************************/

 

 

#include <iostream.h>

#include <fstream.h>

 

void getGrades (int&, int&,int&); //function prototypes

float findAverage (int, int, int );

void print (int, int, int, float);

ofstream outfile; //outfile is declared globally

int main ()

{

outfile.open ("a:grade.dat");

float average;

int grade1, grade2, grade3;

getGrades(grade1, grade2, grade3);

average = findAverage(grade1, grade2, grade3);

print(grade1, grade2, grade3, average);

outfile.close();

return(0);

}

void getGrades (int &c, int &b, int &a) // variable names changed purposely

{

cout << "Enter first grade ----------> ";

cin >> c;

cout << "Enter second grade -----------> ";

cin >> b;

cout << "Enter third grade ---------- > ";

cin >> a;

outfile << "\nEnter first grade ----------> " << c;

outfile << "\nEnter second grade -----------> " << b;

outfile << "\nEnter third grade ---------- > " << a;

}

float findAverage (int one, int two, int three) //variable names changed purposely

{

int total;

float a;

total = one+two+three;

a = (total)/3.0;

return a;

}

 

 

void print (int grade1, int grade2, int grade3, float average)

{

cout << "\nThree grades entered are: " << grade1 << " " <<grade2 << " " << grade3;

cout << "\nAverage is " << average <<endl;

outfile << "\nThree grades entered are: " << grade1 << " " <<grade2 << " " << grade3;

outfile << "\nAverage is " << average <<endl;

}

 

 

Enter first grade ----------> 92

Enter second grade -----------> 88

Enter third grade ---------- > 86

Three grades entered are: 92 88 86

Average is 88.6667

Press any key to continue

 

 

Inline Functions:

We can write a function that is so small that it will fit in one line. For example the findAverage function can be written like this:

inline float findAverage (int a, int b, int c) {return (a+b+c)/3.0;};

/*************************************

Program to find average of 3 grades

objective: Review functions

Program by Dr. Abraham

**************************************/

 

 

#include <iostream.h>

#include <fstream.h>

 

void getGrades (int&, int&,int&); //function prototypes

inline float findAverage (int a, int b, int c) {return (a+b+c)/3.0;};

void print (int, int, int, float);

ofstream outfile; //outfile is declared globally

int main ()

{

outfile.open ("a:grade.dat");

float average;

int grade1, grade2, grade3;

getGrades(grade1, grade2, grade3);

average = findAverage(grade1, grade2, grade3);

print(grade1, grade2, grade3, average);

outfile.close();

return(0);

}

void getGrades (int &c, int &b, int &a) // variable names changed purposely

{

cout << "Enter first grade ----------> ";

cin >> c;

cout << "Enter second grade -----------> ";

cin >> b;

cout << "Enter third grade ---------- > ";

cin >> a;

outfile << "\nEnter first grade ----------> " << c;

outfile << "\nEnter second grade -----------> " << b;

outfile << "\nEnter third grade ---------- > " << a;

}

 

 

void print (int grade1, int grade2, int grade3, float average)

{

cout << "\nThree grades entered are: " << grade1 << " " <<grade2 << " " << grade3;

cout << "\nAverage is " << average <<endl;

outfile << "\nThree grades entered are: " << grade1 << " " <<grade2 << " " << grade3;

outfile << "\nAverage is " << average <<endl;

}

Function Overloading:

It is possible for a function to calculate average of real numbers yielding a real number or to calculate integer average yielding an integer. To do this we have to write two functions with different set of parameters but using the same function name, average. Such functions are called overload functions. When an overloaded function is called, C++ compiler chooses appropriate function based on parameters passed. This will be dealt with at later chapters.


Go to top of this chapter

Site design/development provided by the UTPA NewMedia Center
@1999 The University of Texas-Pan American