# Chapter 16 – Writing Functions

## 16.1  Functions Defined

As your programs get larger and more complex, you will want a way to divide your program into smaller modules.  Chapter 10 gave an introduction to using some of the predefined functions located in other libraries.  An example in the math.h library is the square root function.  To print the square root of 225, you would simply type:

cout << sqrt(225);

Having the code to calculate square roots located in a separate function makes programming much easier.  For example, if you write a lot of programs that need to calculate volumes of various geometric shapes, then it would be beneficial for you to create functions for each of these calculations.  Whenever you need to calculate the volume of a sphere in your program, you would just call that function (instead of writing the code each time).  This chapter will show how to write your own functions.

Functions may be located in the same file as your main program, or they may be located in a separate library file that you can #include in your main program.  Locating functions in the same file as your main program gives you a way to divide up your program into smaller pieces.  Locating functions in a separate library file allows you to put common tasks (e.g. calculating the volume of a sphere) in a library that may be used by any program you write.

## 16.2  Format of a Function

This section will demonstrate a function and explain its format.  The next program demonstrates a function to calculate the volume of a sphere.  In this example, the sphere volume function is located in the same file as the main program.

 Program 16.2a – Sphere Volume Function #include // This is the function to calculate sphere volumes float VolSphere(float Radius) {    return (4.0/3.0) * 3.14 * Radius * Radius * Radius; } int main() {    cout << "Sphere volume with radius of 2.0 is " << VolSphere(2.0) << endl;    cout << "Sphere volume with radius of 5.5 is " << VolSphere(5.5) << endl;   return 0; } Output Sphere volume with radius of 2.0 is 33.4933 Sphere volume with radius of 5.5 is 696.557

In the previous program, there are actually two functions: VolSphere and main.  You might not have realized it, but every program you have written so far has a function – main.  The main function always executes first when you run your program.

The VolSphere function is called in each of the cout statements.  When this happens, the parameter (2.0 or 5.5) is sent to the function.  The function calculates the volume of a sphere with that radius, then returns the answer back to the main program.  The diagram below explains the format of the function.

1       2        3     4
{
}

 1. return type Remember how a function works – you send it information (e.g. a radius), it makes calculations (e.g. calculates the volume of a sphere), then returns the answer back to whatever program called the function.  The return type is the variable type of whatever the function returns.  In this case, the function returns the volume of a sphere, so float was selected as the return type.  If a function has a return type of void, then it does not return anything. 2. function name VolSphere is the name you give the function.  When you call the function from your main program, you will put the function name followed by the parameter(s).  Like any C++ variable name, the function name must begin with a letter and cannot contain spaces. 3. parameter type When your main program calls a function, you put the function name followed by any information (parameters) needed by the function.  When you call the VolSphere function, you must send it one parameter – a radius.  The parameter type is the variable type of the parameter sent to the function. 4. parameter name This is the name of the parameter.  In program 15.2a, the first cout statement calls the VolSphere function and sends it one parameter – 2.0.  Inside the VolSphere function, the variable Radius takes on the value of the parameter – 2.0.  Note that Radius is a local variable (only visible in the VolSphere function) and should not be used in your main program.

After the function header line, you will have an opening and closing brace, as with the main program.  Inside the braces, you may make calculations, declare variables, etc.  The last thing your function should do is return a value to the calling program.

Remember: When you call a function, you send it one or more pieces of information (parameters), and it returns a value.  While you are learning how functions work, it is better not to put any cout or cin statements in them.  They should be like a black box – information goes in, and information comes out.  There should not be any side effects such as cout statements.

The next program shows an example of a function to calculate the area of a triangle.  This function takes two parameters – the base and the height of a triangle.

 Program 16.2b – Area of Triangle Function #include float AreaTriangle(float Base, float Height) {    float Volume = 0.5 * Base * Height;    return Volume; } int main() {    cout << "This program calculates the area of a triangle.\n";    float B, H;    cout << "Enter the base: ";    cin >> B;    cout << "Enter the height: ";    cin >> H;    cout << "The area is " << AreaTriangle(B,H) << endl;    return 0; } Output This program calculates the area of a triangle. Enter the base: 3 Enter the height: 4 The area is 6

## 16.3  Function Prototypes

In the previous two programs, the VolSphere and AreaTriangle functions were both located above the main function.  If you were to place these functions below main, the compiler would give you an error.  As with variables, functions must be declared before they are used.  As your programs become more complex, you may have functions that call other functions.  The order that you place your functions can become a hassle.  Therefore, it is good practice to place function prototypes at the top of your program.  Prototypes will declare your functions to the compiler so that the order they are located in your program does not matter.  A prototype for the VolSphere function is just the header line of the function followed by a semicolon:

The next program demonstrates the sphere volume program using a function prototype.

 Program 16.3 – Function Prototype #include float VolSphere(float Radius); int main() {    cout << "Sphere volume with radius of 2.0 is " << VolSphere(2.0) << endl;    cout << "Sphere volume with radius of 5.5 is " << VolSphere(5.5) << endl;    return 0; } float VolSphere(float Radius) {   return (4.0/3.0) * 3.14 * Radius * Radius * Radius; } Output Sphere volume with radius of 2.0 is 33.4933 Sphere volume with radius of 5.5 is 696.557

## 16.4  Function Libraries

You may want to create a library of commonly used functions.  For example, you may want to put the functions for calculating areas and volumes in a separate file that may be included in any program you write.  This will allow you to calculate the volume of a sphere by simply including your library file and calling the VolSphere function.  To do this, simply use your editor to create another file that contains your functions.  In this next example, we first create a file named geometry.h for our geometry functions:

 // geometry.h file float VolSphere(float Radius) {    return (4.0/3.0) * 3.14 * Radius * Radius * Radius; } float AreaTriangle(float Base, float Height) {    float Volume = 0.5 * Base * Height;    return Volume; }

Now that you have the geometry.h file created, you can use its functions from any program you write.  Notice that when you include geometry.h, you must enclose the filename within double quotes:

#include "geometry.h"

Using the Linux g++ compiler, it is acceptable to name your library files using extensions other than .cpp or .c++.  The files included into your main program are not compiled separately --- they are automatically compiled when you compile your main program.  The next program demonstrates using the geometry.h library file.

 Program 16.4 – Using Functions Located in Another File #include #include "geometry.h" int main() {    cout << "Sphere volume with radius of 2.0 is " << VolSphere(2.0) << endl;    cout << "Sphere volume with radius of 5.5 is " << VolSphere(5.5) << endl;    return 0; } Output Sphere volume with radius of 2.0 is 33.4933 Sphere volume with radius of 5.5 is 696.557

## Exercises – Chapter 16

What is the return type and parameters needed to write the following functions?  This exercise is to help you begin thinking how a function works: you send it one or more pieces of data (the parameters), and it returns a value.

 Function Return Type Parameter(s) Example: A function to calculate the area of a rectangle. float float Base float Height 1. A function to calculate the surface area of a sphere. 2. A function to convert a Fahrenheit temperature to Celsius. 3. A function to convert miles to kilometers. 4. A function to calculate the cube of an integer. 5. A function to calculate the product of three numbers. 6. A function to calculate the number of biscuits that can be made from a given amount of flour, baking powder, butter, and milk. 7. A function that gives the gemstone corresponding to a given month (1 – 12). 8. A function that returns the reverse of a word – e.g. it will return "olleH" if you send it "Hello". 9. A function that returns true if the first letter of a word is a vowel, or false if it is a consonant. 10. A function that returns true or false depending on if a given positive integer is a prime number.

11. Write a function named Area_Circle that calculates the area of a circle.

12. Write a function named Day_Week that returns the day (e.g. "Wednesday") for a given number 1 – 7.

13. Write a function named Reverse_Word that returns the reverse of a word.

14. Write a function named Vowel_First that returns true if the first letter of a word is a vowel, or false if it is a consonant.