FUNCTION: ORGANIZING THE PROGRAM
As problems grow they become more difficult to solve. One problem solving strategy is to break a problem into smaller problems (sub-problems) then solve each of the sub-problems separately. This idea of breaking a big problem into smaller ones is reminiscent of the old expression divide and conquer. Similarly, a big program can be broken into subprograms that can be written and tested independently. Each of these subprograms is known as a function (unit) with a specific action (task) to perform. Normally, an application program (software) consists of thousands of lines of code (instructions). Without an organization (function), it is almost impossible to write, test, use, maintain, or reuse a large program. Can you imagine a team of programmers trying to write and manage a program without using functions?
There are two kinds of functions: built-in functions and user-defined functions. A built-in function is pre-constructed and is available for use in your program. A user-defined function must be built by the programmer.
C/C++ comes with a library of functions that are pre-programmed and ready for use in your program. You are already familiar with the C built-in functions
scanf(...), and printf (...), and the C++ function eof (...).
|
Important Built in Functions
|
|
|
Built-in Function |
Brief Description |
|
pow(n,m) |
A function that computes n to the power of m and is located in #include <cmath>. The library holds other mathematical functions such as sqrt( ) and sin( ).
|
|
strcmp( s1, s2 ) |
|
|
qsort(...) |
A function that sorts data using a highly recursive algorithm known as Quick Sort. The algorithm is discussed in Chapter 12, Sorting.
|
|
binsearch(...) |
A function that searches for a particular data element using the algorithm known as a Binary Search. A Binary Search continuously cuts an array of sorted data elements in half until the correct element is found. Binary search is covered in Chapter 11, Searching.
|
|
time(...) |
A function that returns the current date and time. Library: #include<ctime>
|
|
color(...) |
A function that sets a color for an object.
|
|
rand(...) |
A function that generates a random number. Library: #include <cstdlib>. |
![]()
HOW TO USE A BUILT-IN FUNCTION
It is very simple to use a built-in function; just place the function name in your program where you need to perform the task. Instead of writing your own function, call the built-in function to do the job. Remember to include the proper header file (directives) that contains the function definition.
The program of Figure 6.1a illustrates how to raise a number to a different power. For example, the built-in function pow( 3, 4 ) takes two values 3 and 4 and returns 81 as the result. Figure 6.1a shows the use of pow( ) using four different ways.


Not everything you want to accomplish is pre-programmed (a built-in function). There are times when you must write your own functions. In addition, you may want to know how the built-in functions are programmed. Suppose you want to write a program to find the square, cube or power of a number. How would you proceed? In order to make your own function, you have to name it and program it. You can then use the function name in your main program as if it was a built-in function. Figure 6.2a contains a program with the user defined functions mysquare( x ) and mycube( x ). These functions are used to differentiate and emphasize the user-defined functions versus built-in functions.

![]()
![]()
The function mycube( x ) can also be written with the use of the function mysquare( x ) , as illustrated in the following code fragment:

WHERE DO YOU PLACE A USER FUNCTION?
After you have written a function, where do you place it? There are four answers:
1) Place the function before the main program. The compiler favors this method because the function is known before its usage.
2) Place the function after the main program. Traditionally, this method is preferred because the program outline is shown first in the main program and the function details follow.
3) Place it in a separate file e.g. (squarefile.c or squarefile.cpp). The function's file can be compiled separately and then linked to the main program. A project can be built by adding the names of function files to the project. Each project may contain several function files.
4) Place it in a separate file by extension .h (squarefile.h) and include the file before the main, e.g #include "squarefile.h" , in a similar manner to the built in function #include <iostream.h>.
There are three identifying elements to a function:
1) Function Declaration - also known as a prototype.
2) Function Call - puts the function into use either by the main program or by other function(s).
3) Function Definition - where the body of function resides and the function action is performed.
In C, if the function definition is before the main program there is no need to declare (prototype) the function; however, in C++ prototyping is always needed. There are some compilers that skip the rule when the function is defined before the main.
HOW TO PROTOTYPE A FUNCTION
A function prototype is similar to the declaration of a variable. To prototype a function, you specify the kind of data the function will return (passes out) as well as the kind of data the function will communicate (passes in). There are instances when data is not passed into or out of a function.
You have been using the main program for quite a while but you probably did not realize that the main program is a function. If you look at the main program, it possesses the same form as a function. It has parentheses, braces, and a return value (return 0 is used most of the time). The main program is the main function that calls other functions. The main function can only be called by the operating system.
The overtime pay programs of Figures 6.3a and 6.3b provide the same result. Figure 6.3a does not use a function while Figure 6.3b does. Even though it looks like more work and overhead when using a function, it is beneficial to use a function rather than writing the code directly into the main program.




WHY FUNCTIONS ARE IMPORTANT
There are six specific reasons why functions are important:
1) Functions organize, modularize (by breaking programs into several units), and structure a program by outlining and defining the units separately.
2) Functions make programs easy to read, write, and debug.
3) Redundancy within the program is eliminated when using functions. A function is written once and called as many times as needed.
4) Functions allow for separate compilation. Each function can be written, compiled, and tested individually, and then linked at a later time.
5) Functions allow for reusability. A function can be reused by other programs and is easily maintained.
6) Functions facilitate teamwork. Specific functions can be assigned to individual programmers and then linked when necessary.
Whenever you write a program, divide the program into as many functions as possible, even if doing so causes more coding. The use of functions avoids problems. It is important to think of functions rather than writing the whole program as one large unit. Instead of writing the code within the main program, make a function call in main and code the function separately. For example, in the Payroll Program you can use a function to compute overtime pay and another function to find the tax rate. As programs become larger, more functions are added to the program. As you become more familiar with programming, the idea of the function becomes more interesting and useful.
FUNCTIONS AND THE PROGRAM
To use a function in a program you need to follow three steps:
1) Function Declaration – ( also known as known as the function prototype ). You must indicate the return type and the number and type of parameters the function accepts. In the following example the function findmaximum takes three parameters of type integer and returns an integer.
![]()
![]()
2) Function Definition – The function definition provides the actions the function performs. The function header and the body of the function are written here. In Figure 6.4, the function header is shown with the return type as well as the list of input parameters and their respective types. The opening and closing braces indicate the beginning and the end of the function. The return will send the maximum value of the integer input parameters named x, y, and z back to the calling function.


3) Function Call – In order to use a function, the function must be called. To call a function, the name of the function and the correct parameters( if any) must be sent to the function definition. In the example of Figure 6.5a, the main program calls the function named findmaximum. The function finds the maximum of the three integer variables x, y, and z and displays the result. The complete program, including the code from Figure 6.4 is shown below. Figure 6.5b shows sample output of the program.



Each function performs a task on the data passed into the function known as a parameter or argument. It is important to provide the information a function needs to perform the task. One way to provide data to a function is to pass parameters (by listing name(s) and/or value(s)) in the parentheses of the function. In the example:
findmaximum( x, y, z ), the function findmaximum takes three parameters or arguments and finds the maximum of the three.
MATCHING THE PARAMETERS: ACTUAL WITH FORMAL
It is important for the parameters of the calling function to match the parameters of the function definition. When calling a function, the type of parameter and the order of its appearance must be the same as in the function definition. In Figure 6.5a, the function findmaximum passes three parameters, each as an integer value. In the calling function (main program), x, y and z are declared as integers. In the function header, the receiving values are placed in the variable x, y, and z respectively. The arguments or parameters in the calling function (main program) are known as actual arguments. The arguments in the called function are known as formal or dummy arguments. For simplicity, we have chosen the same name as the actual parameters. However, the formal parameter usually has a different name than the actual parameter. Variable names may be different. Notice that the formal variables x, y, and z are declared in the function findmaximum and this sets a separate memory location for x, y, and z.
FUNCTION WITH RETURN VALUE
A function is expected to perform a task and return a result. In the findmaximum function, the function is expected to return the maximum value to the calling function. Figure 6.5a once again illustrates the process.
Sometimes functions do not pass any parameters or return any value. Figure 6.6a illustrates such a program. The program has three functions named readdata, computedata, and printdata. Notice, these three function calls do not send any parameters and do not receive a value in return. You may be wondering if they are built-in system functions or user defined functions.


The two sections listed above and below the function main tell you that these are user- defined functions. These functions need to have source code written by the user that provides functionality when called.
In order to develop the code for these three functions, let us define the actions these functions provide.
|
Readdata |
asks the user to enter three numbers and then store these numbers in variables within the program.
|
|
Computedata |
takes the numbers entered by the user and add them together.
|
|
Printdata |
prints the numbers entered by the user and the result of the computedata calculation. |
Now that we understand what needs to be accomplished, we can start the process of writing the code to accomplish these tasks. The code for readdata is listed in figure 6.6b. Note the function asks the user to enter three numbers. This task is accomplished by using a cout statement asking the user for input. Then a cin statement is used to acquire and store the information provided by the user in the appropriate variables. Also note the use of the keyword void signifies no data is expected; therefore, no parameters are sent to the function and no data is returned from the function. When using the void keyword as a return type, the keyword return is not required at the end of the function definition.

The function named computedata takes all three numbers entered by the readdata function and adds them together. After the addition process, the sum is stored in a variable named sum. Figure 6.6c illustrates the function. Notice the use of the void keyword.

The last function of our program, named printdata, prints to the screen the numbers entered by the user as well as the sum of the inputted three numbers. The program is shown in figure 6.6d.


The next task is to piece the program together by integrating the main program with our user defined functions. How do we link the functions and the main program together?
There are two methodologies:
1) Place the main program first and place the functions after the main.
2) Place the functions first and then place the main program after the functions.
The second methodology is the preferred option. However, I prefer the first option, which allows a reader of a program to view the main first then discover the layout and objective of the program. When further explanation is needed, the reader may look to the functions below for a more detailed explanation. Either way, it all comes down to the style you prefer. The complete program is listed in Figure 6.6e and sample output is shown in Figure 6.6f.
After looking over Figure 6.6e, several questions may arise, such as:
When the program in Figure 6.6e is executed, the function main is called by the operating system. When execution has reached the main, each function is called and returned once the function’s task is complete.
If the declaration of the variables is placed before the function main, then the main program and the entire collection of user defined functions may access these variables. This concept is called variable scoping.
A good exercise would be to move the variables declared above the function main into the function main and see the result. We will discuss global and local variables in more detail in the next few sections.


![]()



LOCAL AND EXTERNAL ( GLOBAL ) VARIABLES
Variables that are declared in the main program or in the functions of a program are said to be local. Variables declared outside of the main program or outside of the functions are said to be global or external. Local variables are variables that are defined locally. Global variables are defined externally.

![]()
![]()

In Figure 6.7a, variables x and y are declared in the main program; therefore, they are local to the main. As a result, myfunction cannot use these variables. However, the variable z is declared outside of the function myfunction and the main program. This allows the use of variable z by both the main program and myfunction.
At a glance, it appears easier to declare all variables outside the main program and all other function. Then every function can access the global variables as needed. So what is the drawback of using global variables? What happens if a function changes the value of a variable by mistake? Is it necessary to make an external variable visible to a function that has no interaction with that variable? A global variable holds its storage for the life of a program, even if it is not needed. Holding storage space for a variable that is not needed takes away resources needed to run a program. For simplicity, use external variables with caution.
EXTERNAL VARIABLE AND THEIR SIDE EFFECTS
If you have a headache, you take a pill. What happens if your headache goes away and you experience some hair loss? The loss of the hair is a side effect of taking the pill. Although this type of situation is rare, it can be costly. Figure 6.8a demonstrates the use of external variables and their unexpected side effect. Observe, the intended output of the program is 8 not 16. Since x is declared as an external variable, the return value of the function findsquare is 4, 4 is then multiplied by the value of x which has been set to 4 in the findsquare function.
![]()


![]()
SCOPE OF NAME
When a variable is declared either locally or externally, the variable has a life span and its own visibility. This determines where the variable exists, is used, and finally where it ceases to exist. When a variable is declared locally, the variables scope starts from the point of declaration and continues to the end of the block. Local variables no longer exist after the block where the variable was declared is exited. A local variable name overrides an external variable with the same name.
| INFORMATION FROM DR. EBRAHIMI'S C++ PROGRAMING EASY WAYS |