0% found this document useful (0 votes)
27 views

Chapter 1 Function

Uploaded by

tesewaka3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Chapter 1 Function

Uploaded by

tesewaka3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Chapter 1

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.

A function call is a statement that causes a function to execute.

A function definition contains the statements that make up the


function.

Functions can be used to define reusable code and organize and


simplify code.

All function definitions have the following parts:


Name
Every function must have a name. In general, the same rules that
apply to variable names also apply to function names.
Parameter list
The parameter list is the list of variables that hold the values being
passed
2
Body
The body of a function is the set of statements that carries out the
task
the function is performing. These statements are enclosed in braces.

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;
}

The first line in the definition is called the function header


3
Void Functions
Some functions simply Perform one or more statements and then
return.

In C++ these are called void functions.


The displayMessage function shown here is an example:

void displayMessage()
{
cout << "Hello from the function displayMessage.\n";
}

The function’s return type is void.


This means the function does not send back a value when it has
finished executing and returns to the part of the program that called it.

Because no value is being sent back, no return statement is required.


4
Calling a Function
A function is executed when it is called.
Function main is called automatically when a program starts, but all
other functions must be executed by function call 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";
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";
}

It is possible to have many functions and function calls in a program.


Example
// This program has three functions: main, first, and second.
#include <iostream>
using namespace std;
8
Calling a Function
//main function
int main()
{
cout << "I am starting in function main.\n";
first(); // Call function first
second(); // Call function second
cout << "Now I am back in function main again.\n";
return 0;
}

// function first . This function displays a message.


void first()
{
cout << "I am now inside the function first.\n";
}

//function second. This function displays a message. 9


Calling a Function

The following illustrates the paths taken by the program

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";
}

//function deeper. This function displays a message.


void deeper()
{
cout << "I am now inside the function deeper.\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.

Before the compiler encounters a call to a particular function, it must


already know the number of parameters the function uses, the data
type of each parameter, and the return type of the function.

A prototype is never needed for main because it is the starting point of


the program.

The three functions main, deep, and deeper, would have to be


organized if it had no function prototypes.
• Function deeper would have to be placed first so that deep could
call it.
• Function deep would have to be placed second so that main could
call it.
• The main function would have to be placed last.
14
Function Prototypes
WARNING!
You must either place the function definition or the function Prototype
ahead of all calls to the function. Otherwise the program will not
compile.

Sending Data into a Function


When a function is called, the program may send values into the
function.

Values that are sent into a function are called arguments.

In the following statement the function pow is being called with two
arguments, 2.0 and 3.0, passed to it:

result = pow(2.0, 3.0);

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;
}

Notice that the parameter variable is defined inside the parentheses


(int num).
Because it is declared to be an integer, the function displayValue can
accept an integer value as an argument.

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.

Others use the terms actual arguments and formal arguments.


Regardless of which set of terms you use, it is important to be consistent.

In the above example, the number 5 is passed into num, which is


displayValue's
parameter. This is illustrated in the following figure.

18
The following program shows the function displayValue being called several
times with a different argument passed each time.

// This program demonstrates a function with a parameter.


#include <iostream>
using namespace std;

// 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;
}

When a function is called, it is best if each argument passed to it has


the same data type as the parameter receiving it. 20
For example, the displayValue function has an integer parameter,
which means it expects to receive an integer value.
If the function is called as shown here,

displayValue(4.7);

the argument will be truncated and the integer 4 will be stored in the
parameter num.

Often it is useful to pass several arguments into a function.


Example
// This program demonstrates a function with three parameters.
#include <iostream>
using namespace std;

// 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;

// Call showSum, passing 3 arguments


showSum(value1, value2, value3);
return 0;
}

/********************************************
* 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.

The following illustrates that when a function with multiple parameters


is called, the arguments are passed to the parameters in order

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.

Passing Data by Value


When an argument is passed into a parameter by value, only a copy
of the argument’s value is passed. Changes to the parameter do not
affect the original argument.

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;

// Call changeMe, passing the value in number as an argument

changeMe(number);

// Display the value in number again


cout <<"Back in main again, number is still " << number << endl;
return 0;
}

//changeMe. This function changes the value stored


//in its parameter myValue
void changeMe(int myValue)
{
// Change the value of myValue to 0
myValue = 0;
25
The following illustrates that a parameter variable’s storage location in
memory is separate from that of the original argument.

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;

cout <<"Enter two numbers and I will divide the first\n";


cout << "number by the second number: ";
cin >> num1 >> num2;
divide(num1, num2); 27
The return Statement

/**************************************************
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.

Functions that return a value are known as value-returning functions.

Although several arguments can be passed into a function, only one


value can be returned from it.

Think of a function as having multiple communication channels for


receiving data (parameters), but only one channel for sending data
(the return value).
This is illustrated in the following figure.

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.

Here is an example of a function that returns an int value:


int sum(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}
The name of this function is sum. Notice in the function header that
the return type is int, as illustrated in the following figure

30
A value-returning function must have a return statement written in the
following general format:
return expression;

The prototype for a value-returning function follows the same


conventions Here is the prototype for the sum function:
int sum(int num1, int num2);

Calling a Value-Returning Function


The following shows an example of how to call the sum function.

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

// Call the sum function, passing the contents of


// value1 and value2 as arguments. Assign the return
// value to the total variable.
total = sum(value1, value2);

// Display the sum of the values


cout << "The sum of " << value1 << " and "
<< value2 << " is " << total << endl;
return 0;
}

/*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.

You can do many other things with the return values.


For example, the following code shows a math expression that uses a
call to the sum function:
int x = 10, y = 15;
double average;
average = sum(x, y) / 2.0;

Here is another example: 33


Returning a Boolean Value
Functions may return true or false values.
For example, the isValid function shown below accepts an int
argument and
returns true if the argument is within the range of 1 through 100, or
false otherwise.
bool isValid(int number)
{
bool status;
if (number >= 1 && number <= 100)
status = true;
else
status = false;
return status;
}
The following code shows an if/else statement that makes a call to the
function:
int value = 20;
if (isValid(value)) 34
Example
// This program uses a function that returns true or false.
#include <iostream>
using namespace std;
// Function prototype
bool isEven(int);
int main()
{
int val; // the value to be tested

// Get a number from the user


cout << "Enter an integer and I will tell you ";
cout << "if it is even or odd: ";
cin >> val;

// Indicate whether it is even or odd


if (isEven(val))
cout << val << " is even.\n"; 35
Example
/**************************************************
isEven *
* This Boolean function tests if the integer
argument it receives is even or odd. It returns
true if the argument is even and false if it is
odd. *********************************************/
bool isEven(int number)
{
if (number % 2 == 0)
return true; // The number is even if there's no
remainder

else
return false; // Otherwise, the number is odd
}

36
Let’s compare three different ways to write the Boolean returning
function.

// Version 1

Using Functions in a Menu-Driven Program


Functions are ideal for use in menu-driven programs.
When the user selects an item from a menu, the program can call the
appropriate function. 37
Clearing the Screen
Here is the command for Unix-based operating systems, such as
Linux and Mac OS:
system("clear");

And here is the command for Windows operating systems.


system("cls");

Local and Global Variables


A local variable is defined inside a function and is not accessible
outside the function.

A global variable is defined outside all functions and is accessible to


all functions in its scope.

NOTE: The parameters of a function are also local variables. Their


scope is limited to the body of the function.
38
Global Variables

Local Variables

Instructions

39
Although global variables can be useful, you should restrict your use
of them.
Here is why.

• Global variables make debugging difficult.


• Functions that use global variables are usually dependent on
those variables.
• Global variables make a program hard to understand.

It is best not use global variables for storing, manipulating, and


retrieving data.

Instead, declare variables locally and pass them as arguments to the


functions that need to access them.

it is generally permissible to use global constants in a program.


40
You cannot have two local variables with the same name in the same
function.

you can have a parameter or local variable with the same name as a
global
variable or constant.

When you do this, the name of the parameter or local variable


shadows the name of the 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;

void ethiopia(); // Function prototype

const int BIRDS = 500; // Global constant 41


cout << "In main there are " << BIRDS << "
birds.\n";
ethiopia();
return 0;
}

/*******************************
* 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.

This is because local variables are destroyed when a function


terminates and are then re-created when the function starts again.

Example

// This program shows that local variables do not retain


// their values between function calls.
#include <iostream>
using namespace std;

void showLocal(); // Function prototype

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

cout << "localNum is " << localNum << endl;


localNum = 99;
}

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.

Static local variables are not destroyed when a function returns.

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;

void showStatic(); // Function prototype

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

cout << "This function has been called "


<< ++numCalls << " times. " << endl;
}

46
Default Arguments
Default arguments are passed to parameters automatically if no
argument is provided in the function call.

The default arguments are usually listed in the function prototype.


Here is an example:

void showArea(double length = 20.0, double width = 10.0);

Because parameter names are not required in function prototypes,


the example prototype could also be declared like this:

void showArea(double = 20.0, double = 10.0);

Here is the definition of the function:

void showArea(double length, double width)


{ 47
Because both parameters have default arguments, they may
optionally be omitted in the function call, as shown here:
showArea();

The output of the function will be


The area is 200

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 following function call, arguments are supplied for both


parameters:
showArea(12.0, 5.5); 48
NOTE:
A function’s default arguments should be assigned in the earliest
occurrence of the function name. This will usually be the function
prototype. However, if a function does not have a prototype, default
arguments may be specified in the function header. The showArea
function could be defined as follows:

void showArea(double length = 20.0, double width =10.0)


{
double area = length * width;
cout << "The area is " << area << endl;
}

When an argument is left out of a function call, all arguments that


come after it must be left out as well.
In the showArea function, it is not possible to omit the argument for
length without also omitting the argument for width. For example, the
following function call would be illegal:
49
It is possible, however, for a function to have some parameters with
default arguments and some without. For example, in the following
function, only the last parameter has a default argument:
// Function prototype
void calcPay(int empNum, double payRate, double hours = 40.0);

// Definition of function calcPay


void calcPay(int empNum, double payRate, double hours)
{
double wages;
wages = payRate * hours;
cout << "Gross pay for employee number ";
cout << empNum << " is " << wages << endl;
}
When calling this function, arguments must always be specified for
the first two parameters (empNum and payRate) because they have
no default arguments.
Here are examples of valid calls:
50
When a function uses a mixture of parameters with and without
default arguments, the parameters with default arguments must be
declared last.

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);

Using Reference Variables as Parameters


A reference variable is a variable that references the memory location
of
another variable.
51
Reference variables are defined like regular variables, except there is
an ampersand (&) between the data type and the name.

For example, the following function definition makes the parameter


refVar a reference variable:

void doubleNum(int &refVar)


{
refVar *= 2;
}

NOTE: The variable refVar is called “a reference to an int.”

All of the following prototypes for the doubleNum function are correct.

void doubleNum(int &refVar);


void doubleNum(int& refVar);
void doubleNum(int &); 52
NOTE: The ampersand must appear in both the prototype and the
header of any function that uses a reference variable as a parameter.
It does not appear in the function call.

Example
// This program uses a reference variable as a function parameter.

#include <iostream>
using namespace std;

// Function prototype. The parameter is a reference variable.


void doubleNum(int &refVar);

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.

If a function has more than one parameter that is a reference variable,


you must use an ampersand for each of them in both the prototype
and the function header.
Here is the prototype for a function that uses four reference variable
parameters:
void addThree(int& num1, int& num2, int& num3, int& sum);

and here is the function definition:


void addThree(int& num1, int& num2, int& num3, int& sum)
{
cout << "Enter three integer values: ";
cin >> num1 >> num2 >> num3;
sum = num1 + num2 + num3;
} 55
When to Pass Arguments by Reference and When to Pass
Arguments by Value

Here are some general guidelines.


• When an argument is a constant, it must be passed by value. Only
variables can be passed by reference.

• When a variable passed as an argument should not have its value


changed, it should be passed by value. This protects it from being
altered.

• When exactly one value needs to be “sent back” from a function


to the calling routine, it should generally be returned with a return
statement rather than through a reference parameter.

• When two or more variables passed as arguments to a function


need to have their values changed by that function, they should be
passed by reference.

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

• When a function must change existing values in the calling


function

• When a file stream object is passed to a function

Passing Files to Functions


Reference parameters should always be used when a file stream
object is passed to a 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;

while (someFile >> temperature)


cout << temperature << " ";
cout << endl;
}

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;
}

The exit() Function 62


// 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;
}

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.

Arrays as Function Arguments


Individual elements of arrays and entire arrays can both be passed as
arguments to functions.

When an entire array is passed to a function, it is not passed by


value.
64
Example
// This program shows how to pass an entire array to a function.
#include <iostream>
using namespace std;

void showValues(int intArray[], int size); //


Function prototype

int main()
{
const int ARRAY_SIZE = 8;
int collection[ARRAY_SIZE] = {5, 10, 15, 20,
25, 30, 35, 40};

cout << "The array contains the values\n";


showValues(collection, ARRAY_SIZE);
return 0;
} 65
/*************************************************************
* showValues *
* This function displays the contents of an integer array *
* when passed the array's address and its size as arguments.*
*************************************************************/
void showValues (int nums[], int size)
{
for (int index = 0; index < size; index++)
cout << nums[index] << " ";
cout << endl;
}

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.

Here is the definition of a function that uses a pointer parameter:

void doubleValue(int *val)


{
*val *= 2;
}

When the function is called, the address of the variable that is to be


doubled
must be used as the argument, not the variable itself.

Here is an example of a call to the doubleValue function:


67
Example
// This program uses two functions that accept
// addresses of variables as arguments.
#include <iostream>
using namespace std;

// Function prototypes
void getNumber(int *);
void doubleValue(int *);

int main()
{
int number;
// Call getNumber and pass the address of number
getNumber(&number);

// Call doubleValue and pass the address of number


doubleValue(&number); 68
/**************************************************Definition of
getNumber. The parameter, input, is a pointer. This function
asks the user for a number. The value entered is stored in the
variable *
pointed to by input. *
**************************************************/

void getNumber(int *input)


{
cout << "Enter an integer number: ";
cin >> *input;
}

/*************************************************
Definition of doubleValue. The parameter, val, is a pointer.
This function multiplies the variable *
pointed to by val by two.
**************************************************/

void doubleValue(int *val)


69
Pointers can be used with structures.
C++ provides the structure pointer operator −> to use when you want
to access a member of a structure through a pointer

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.

Because it is not desirable to take the time to copy an entire structure,


unless it is quite small, structures are normally passed to functions by
reference.

If you do not want a function to change any member variable values,


the structure variable should be passed to it as a constant reference.

A structure variable can also be returned from a function. In this case


the return type of the function is the name of the structure.

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;

struct InvItem // Holds data for an inventory item


{
int partNum; // Part number
string description; // Item description
int onHand; // Units on hand
double price; // Unit price
};

// 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.

Look at this message function:


void message()
{
cout << "This is a recursive function.\n";
message();
}

This function displays the string "This is a recursive function.\n" and


then calls itself. Each time it calls itself, the cycle is repeated.

There’s no way to stop the recursive calls. This function is like an


infinite
loop because there is no code to stop it from repeating.

a recursive function must have a way of controlling the number of 78


The following is a modification of the message function.

It passes an integer argument that holds the number of times the


function is to call itself.
void message(int times)
{
if (times > 0)
{
cout << "This is a recursive function.\n";
message(times − 1);
}
}

As long as the times argument is greater than zero, it will display the
message and call itself again.

Each time it calls itself, it passes times – 1 as the argument.


79
The argument, 3, will cause the function to be called four times.

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:

Because there are no more statements to be executed after the


function call, the third instance of the function returns control of the
program to the second instance.

This repeats until all instances of the function return.


81
Example
// This program demonstrates a simple recursive function.
#include <iostream>
using namespace std;

// 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);
}
}

To further illustrate the inner workings of this recursive function, let’s


look at another version of the program.
83
// This program demonstrates a simple recursive function.
#include <iostream>
using namespace std;

// 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.

This breaking-down process stops when it reaches a base case, that


is, a subproblem that is simple enough to be solved directly.

For example, in the recursive message function of the preceding


examples, the base case is when the parameter times is 0.

The Recursive Factorial Function


The recursive factorial function accepts an argument and calculates
its factorial. Its base case is when the argument is 0.

In mathematics, the notation n! represents the factorial of the number


n. The factorial of an integer n is defined as

86
We can define the factorial of a number using recursion as follows:

The C++ implementation of this recursive definition is


int factorial(int num)
{
if (num == 0) // base case
return 1;
else
return num * factorial(num – 1);
}

Consider a program that displays the value of 3! with the following


statement:
cout << factorial(3) << endl;
The first time the function is called, num is set to 3. The if statement
87
Although this is a return statement, it does not immediately return.

Before the return value can be determined, the value of factorial(num


– 1) must be determined.

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;

cout << "Enter an integer value and I will display\n";


cout << "its factorial: ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number) << endl; 89
//****************************************************
// Definition of factorial. A recursive function to *
// calculate the factorial of the parameter, num. *
//****************************************************
int factorial(int num)
{
if (num == 0) //base case
return 1;
else
return num * factorial(num - 1);
}

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

You might also like