Chapter 1 Function
Chapter 1 Function
Function
Contents
• Defining and Calling Functions
• Function Prototypes
• Sending Data into a Function
• Passing Data by Value
• The return Statement
• Returning a Value from a Function
• Returning a Boolean Value
• Using Functions in a Menu-Driven Program
• Local and Global Variables
• Static Local Variables
• Default Arguments
• Using Reference Variables as Parameters
• Overloading Functions
• The exit() Function
• Arrays as Function Arguments 1
Defining and Calling Functions
A function is a collection of statements that performs a specific task.
Return type
A function can send a value back to the program module that called it.
The return type is the data type of the value being sent back.
Example
Return Name
Type
Parameter list
(This one is empty)
int main( )
{ Body
cout<<“Hello World!\n”;
return 0;
}
void displayMessage()
{
cout << "Hello from the function displayMessage.\n";
}
Example
// This program has two functions, main and displayMessage.
#include <iostream>
using namespace std;
// Function prototype
void displayMessage();
// main
int main()
{
cout << "Hello from main.\n";
displayMessage(); // Call displayMessage
cout << "Now we are back in the main function again.\n";
return 0; 5
Calling a Function
//displayMessage. This function displays a greeting.
void displayMessage()
{
cout << "Hello from the displayMessage function.\n";
}
6
Calling a Function
Function call statements may be used in control structures
such as loops, if statements, and switch statements.
Example
// This program has two functions, main and displayMessage.
#include <iostream>
using namespace std;
// Function prototype
void displayMessage();
// main
int main()
{
cout << "Hello from main.\n";
for(int count = 0; count < 3; count++){
displayMessage(); // Call displayMessage
}
cout << "Now we are back in the main function again.\n";
return 0; 7
Calling a Function
//displayMessage. This function displays a greeting.
void displayMessage()
{
cout << "Hello from the displayMessage function.\n";
}
10
Calling a Function
Functions may also be called in a hierarchical, or layered, fashion.
Example
// This program has three functions: main, deep, and deeper.
#include <iostream>
using namespace std;
// Function prototypes
void deep();
void deeper();
//main
int main()
{
cout << "I am starting in function main.\n";
deep(); // Call function deep
cout << "Now I am back in function main again.\n";
return 0; 11
Calling a Function
//function deep. This function displays a message.
void deep()
{
cout << "I am now inside the function deep.\n";
deeper(); // Call function deeper
cout << "Now I am back in deep.\n";
}
12
Calling a Function
Function Prototypes
A function prototype eliminates the need to place a function definition13
Function Prototypes
A function prototype eliminates the need to place a function definition
before all calls to the function.
In the following statement the function pow is being called with two
arguments, 2.0 and 3.0, passed to it:
This will compute the value of 2.0 to the third power and return the
value 8.0 to be stored in result. 15
WARNING!
Here is the definition of a function that has a parameter. The
parameter is num.
void displayValue(int num)
{
cout << "The value is " << num << endl;
}
Example
// This program demonstrates a function with a parameter.
#include <iostream>
using namespace std;
16
int main()
{
cout << "I am passing 5 to displayValue.\n";
displayValue(5); // Call displayValue with argument 5
cout << "Now I am back in main.\n";
return 0;
}
/********************************************
* displayValue *
* This function uses an integer parameter *
* whose value is displayed. *
********************************************/
void displayValue(int num)
{
cout << "The value is " << num << endl;
}
17
The function prototype could have been written like this:
void displayValue(int); // Function prototype
NOTE:
In this chapter, the values that are passed into a function are called
arguments, and the variables that receive those values are called
parameters.
However, there are several variations of these terms in use. Some call the
arguments actual parameters and the parameters formal parameters.
18
The following program shows the function displayValue being called several
times with a different argument passed each time.
// Function prototype
void displayValue(int num);
int main()
{
cout << "I am passing 5 to displayValue.\n";
displayValue(5); // Call displayValue with argument 5
displayValue(10); //Call displayValue with argument 10
displayValue(2); // Call displayValue with argument 2
displayValue(16); // Call displayValue with argument 16
cout << "Now I am back in main.\n";
return 0;
19
/********************************************
* displayValue *
* This function uses an integer parameter *
* whose value is displayed. *
********************************************/
void displayValue(int num)
{
cout << "The value is " << num << endl;
}
displayValue(4.7);
the argument will be truncated and the integer 4 will be stored in the
parameter num.
// Function prototype
void showSum(int num1, int num2, int num3);
21
// Get 3 integers
cout << "Enter three integers and I will display ";
cout << "their sum: ";
cin >> value1 >> value2 >> value3;
/********************************************
* showSum *
* This function displays the sum of the *
* 3 integers passed into its parameters. *
********************************************/
void showSum(int num1, int num2, int num3)
{
cout <<"The sum is "<< (num1 + num2 + num3) << endl;22
Note
the showSum parameter variables cannot be defined like this:
void showSum(int num1, num2, num3) // Error!
whereas the function prototype and function header must list the data
type of each parameter, the call to the function must not list any data
types.
23
Note that although the names of the arguments passed to a function
do not need to match the names of the function parameters receiving
them, the arguments must match the parameters in number, in order,
and in data type.
Example
// This program demonstrates that changes to a function
// parameter have no effect on the original argument.
#include <iostream>
using namespace std;
// Function Prototype
void changeMe(int aValue);
24
// Display the value in number
cout << "In main number is " << number << endl;
changeMe(number);
26
The return Statement
The return statement causes a function to end immediately.
//This program uses a function to perform division.
// It illustrates the return statement.
#include <iostream>
using namespace std;
// Function prototype
void divide(double arg1, double arg2);
int main()
{
double num1, num2;
/**************************************************
divide. This function uses two parameters, arg1
and arg2. If arg2 does not = zero, the function
displays the result of arg1/arg2. Otherwise it
returns without *performing the division. *
**************************************************/
void divide(double arg1, double arg2)
{
if (arg2 == 0.0)
{
cout << "Sorry, I cannot divide by zero.\n";
return;
}
cout << "The quotient is " << (arg1 / arg2) << endl;
}
28
Returning a Value from a Function
A function may send a value back to the part of the program that
called
the function.
29
Defining a Value-Returning Function
When you are writing a value-returning function, you must decide
what type of value the function will return.
This is because you must specify the data type of the return value in
the function header and function prototype.
30
A value-returning function must have a return statement written in the
following general format:
return expression;
Example
// This program uses a function that returns a value.
#include <iostream>
using namespace std;
// Function prototype
int sum(int num1, int num2); 31
value2 = 40, // The second value
total; // Holds the returned total
/*sum
* This function returns the sum of its two
parameters. */
int sum(int num1, int num2) 32
The following figure shows how the arguments are passed into the
function and how a value is passed back from the function.
else
return false; // Otherwise, the number is odd
}
36
Let’s compare three different ways to write the Boolean returning
function.
// Version 1
Local Variables
Instructions
39
Although global variables can be useful, you should restrict your use
of them.
Here is why.
you can have a parameter or local variable with the same name as a
global
variable or constant.
Example
// This program demonstrates how a local variable or constant
// can shadow the name of a global variable or constant.
#include <iostream>
using namespace std;
/*******************************
* ethiopia *
*******************************/
void ethiopia()
{
const int BIRDS = 10000;
cout << "In ethiopia there are " << BIRDS <<
" birds.\n";
}
42
If a function is called more than once in a program, the values stored
in the function’s local variables do not persist between function calls.
Example
int main()
{
showLocal();
43
/**************************************************
*showLocal *
* This function sets, displays, and then changes
the value of local variable localNum before
returning. *
**************************************************/
void showLocal()
{
int localNum = 5; // Local variable
44
If it is desirable for a program to “remember” what value is stored
in a local variable between function calls, make the variable static.
They exist for the entire lifetime of the program, even though their
scope is only the function in which they are defined.
Example
// This program uses a static local variable.
#include <iostream>
using namespace std;
int main()
{
// Call the showStatic function five times 45
/**************************************************
* showStatic *
* This function keeps track of how many times it *
* has been called by incrementing a static local *
* variable, numCalls, each time it is called. *
**************************************************/
void showStatic()
{
static int numCalls = 0; // Static local variable
46
Default Arguments
Default arguments are passed to parameters automatically if no
argument is provided in the function call.
The default arguments are only used when the actual arguments are
omitted from the function call. In the following call, the first argument
is specified, but the second is omitted:
showArea(12.0);
The value 12.0 will be passed to length, while the default value 10.0
will be passed to width. The output of the function will be
The area is 120
In the calcPay function, hours could not have been declared before
either of the other parameters. The following prototypes are illegal:
// Illegal prototype
void calcPay(int empNum, double hours = 40.0, double payRate);
// Illegal prototype
void calcPay(double hours = 40.0, int empNum, double payRate);
All of the following prototypes for the doubleNum function are correct.
Example
// This program uses a reference variable as a function parameter.
#include <iostream>
using namespace std;
int main()
{
int value = 4;
cout << "In main, value is " << value << endl;
cout << "Now calling doubleNum. . ." << endl;
53
/**************************************************************
* doubleNum *
* This function's parameter is a reference variable. The & *
* tells us that. This means it receives a reference to the *
* original variable passed to it, rather than a copy of that *
* variable's data. The statement refVar *= 2 is doubling the *
* data stored in the value variable defined in main. *
**************************************************************/
void doubleNum (int &refVar)
{
refVar *= 2;
}
54
NOTE:
Only variables may be passed by reference. If you attempt to pass a
nonvariable argument, such as a literal, a constant, or an expression,
into a reference parameter, an error will result.
56
Here are three common instances when reference parameters are
used.
• When data values being input in a function need to be known by
the calling function
Example
// This program reads a set of daily high temperatures from a file
// and displays them. It demonstrates how to pass a file to a
// function. The function argument, which is a file stream object,
57
void readFile(ifstream&); // Function prototype
int main()
{
ifstream inputFile;
inputFile.open("weather.dat");
if (inputFile.fail())
cout << "Error opening data file.\n";
else
{
readFile(inputFile);
inputFile.close();
}
return 0;
}
58
/********************************************************
* readFile *
* This function reads and displays the contents of the *
* input file whose file stream object is passed to it. *
********************************************************/
void readFile(ifstream &someFile)
{
int temperature;
Program Output
72 83 71 69 75 77 70
59
Overloading Functions
Two or more functions may have the same name, as long as their
parameter lists are different.
Example
// This program uses overloaded functions.
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototypes
int square(int);
double square(double);
int main()
{
int userInt;
double userReal; 60
// Display their squares
cout << "Here are their squares: ";
cout <<fixed <<showpoint << setprecision(2);
cout << square(userInt) << " and " << square(
userReal) << endl;
return 0;
}
/***************************************************
* overloaded function square *
* This function returns the square of the value *
* passed into its int parameter. *
***************************************************/
int square(int number)
{
return number * number;
}
61
/***************************************************
* overloaded function square *
* This function returns the square of the value *
* passed into its double parameter. *
***************************************************/
double square(double number)
{
return number * number;
}
// Function prototype
void someFunction();
int main()
{
someFunction();
return 0;
}
void someFunction()
{
cout << "This program terminates with the exit function.\n";63
You can use C++ named constants arguments for the exit function
such as exit(EXIT_SUCCESS); or exit(EXIT_FAILURE); to indicate
successful exit or unsuccessful exit respectively.
To use the exit function and the constants, you must include the
cstdlib header file.
WARNING!
The exit() function unconditionally shuts down your program.
Because it bypasses a program’s normal logical flow, you should use
it with caution.
int main()
{
const int ARRAY_SIZE = 8;
int collection[ARRAY_SIZE] = {5, 10, 15, 20,
25, 30, 35, 40};
66
Pointers as Function Parameters
A pointer can be used as a function parameter. It gives the function
access to the original argument, much like a reference parameter
does.
// Function prototypes
void getNumber(int *);
void doubleValue(int *);
int main()
{
int number;
// Call getNumber and pass the address of number
getNumber(&number);
/*************************************************
Definition of doubleValue. The parameter, val, is a pointer.
This function multiplies the variable *
pointed to by val by two.
**************************************************/
Example
#include <iostream>
using namespace std;
struct per{
string name;
int age;
};
int main()
{
per person;
per *ptr = &person;
ptr->name="Robel";
ptr->age = 25;
cout<<ptr->name; 70
Passing Structures to Functions
Structure variables can be passed to functions by value, by reference,
and by constant reference.
By default, they are passed by value. This means that a copy of the
entire original structure is made and passed to the function.
71
Example
// This program passes a structure variable to one function
// by reference and to another as a constant reference.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// Function prototypes
void getItemData(InvItem &); // Function 72
void showItem(const InvItem &);
// Function showItem will receive an
// InvItem structure passed to it as a
// constant reference because showItem
// just needs display member variable
// values, not change them.
int main()
{
InvItem part; // Define an InvItem structure variable.
getItemData(part);
showItem(part);
return 0;
}
73
/********************************************************************
* getItemData *
* This function stores data input by the user in the members of an *
* InvItem structure variable passed to the function by reference. *
* ******************************************************************/
void getItemData(InvItem &item)
{
cout << "Enter the part number: ";
cin >> item.partNum;
cout << "Enter the part description: ";
cin.get(); // Move past the '\n' left in the
// input buffer by the last input.
getline(cin, item.description);
cout << "Enter the quantity on hand: ";
cin >> item.onHand;
cout << "Enter the unit price: ";
cin >> item.price;
} 74
/********************************************************************
* showItem *
* This function displays the data stored in the members of an *
* InvItem structure variable passed to it as a constant reference. *
* ******************************************************************/
void showItem(const InvItem &item)
{
cout << fixed << showpoint << setprecision(2) << endl;
cout << "Part Number : " << item.partNum << endl;
cout << "Description : " << item.description << endl;
cout << "Units On Hand: " << item.onHand << endl;
cout << "Price : $" << item.price << endl;
}
75
The exit() Function
The exit() function causes a program to terminate, regardless of
which function or control mechanism is executing.
Example
/* This program shows how the exit function causes
a program to stop executing.*/
#include <iostream>
#include <cstdlib> // Needed to use the exit function
using namespace std;
// Function prototype
void someFunction();
int main()
{
someFunction();
return 0; 76
/****************************************************************
* someFunction *
* This function demonstrates that exit() can be used to end *
* a program from a function other than main. This is not *
* considered good programming practice and should normally *
* be done only to signal that an error condition has occurred. *
****************************************************************/
void someFunction()
{
cout << "This program terminates with the exit function.\n";
cout << "Bye!\n";
exit(0);
cout << "This message will never be displayed\n";
cout << "because the program has already terminated.\n";
}
77
Introduction to Recursion
A recursive function is one that calls itself.
As long as the times argument is greater than zero, it will display the
message and call itself again.
As you can see from the following figure, the function will be called
four times, so the depth of recursion is four.
When the function reaches the fourth call, the times parameter will be
set to 0.
80
At that point, the if statement will stop the recursive chain of calls, and
the fourth instance of the function will return.
Control of the program will return from the fourth instance of the
function to the point in the third instance directly after the recursive
function call:
// Function prototype
void message(int);
int main()
{
message(3);
return 0;
}
//***********************************************************
// Definition of function message. If the value in times *
// is greater than 0, the message is displayed and the *
// function is recursively called with the argument * 82
void message(int times)
{
if (times > 0)
{
cout << "Message " << times << "\n";
message(times - 1);
}
}
// Function prototype
void message(int);
int main()
{
message(3);
return 0;
}
//***********************************************************
// Definition of function message. If the value in times *
// is greater than 0, the message is displayed and the *
// function is recursively called with the argument *
// times - 1. * 84
void message(int times)
{
cout << "Message " << times << ".\n";
if (times > 0)
{
message(times - 1);
}
cout << "Message " << times << " is returning.\n";
}
85
Recursive functions work by breaking a complex problem down into
subproblems of the same type.
86
We can define the factorial of a number using recursion as follows:
The function is called recursively until the fourth call, in which the num
parameter will be set to zero.
The following diagram illustrates the value of num and the return
value
during each call of the function.
88
Example
// This program demonstrates a recursive function
// to calculate the factorial of a number.
#include <iostream>
using namespace std;
// Function prototype
int factorial(int);
int main()
{
int number;
90
The Recursive gcd Function
Using Euclid’s algorithm, the greatest common divisor, or gcd, of two
positive integers, x and y, is
Example
// This program demonstrates a recursive function to
// calculate the greatest common divisor (gcd) of two numbers.
#include <iostream>
using namespace std;
// Function prototype
int gcd(int, int);
int main()
{
int num1, num2; 91
cout << "The greatest common divisor of " << num1;
cout << " and " << num2 << " is ";
cout << gcd(num1, num2) << endl;
return 0;
}
//*********************************************************
// Definition of gcd. This function uses recursion to *
// calculate the greatest common divisor of two integers, *
// passed into the parameters x and y. *
//*********************************************************
int gcd(int x, int y)
{
if (x % y == 0) //base case
return y;
else
return gcd(y, x % y);
} 92
Select this paragraph to edit
Thank you!
93