Chapter 6 Functions: Learning Objective
Chapter 6 Functions: Learning Objective
Chapter 6
Functions
Learning objective
Upon completion of this chapter, students will:
be able to define and declare functions in a program
be able to use function prototypes in a program
be able to understand the flow of a program when functions are used
be able to call functions and pass parameters to functions in a program
be able to use standard library functions in a program
Why use functions?
Add all integers from 1 to 10.
// intSum1.cpp
#include <iostream>
using namespace std;
/* - To calculate the result of adding all
integers from 1 to 10.
Problem: If we want to add all integers from 1 to 20 or even
to a larger number, the line will be very long.
*/
int main()
{
int sum;
// This line is quite long. Programming in this way is clumsy.
sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
cout << "Adding from 1 to 10 equals " << sum << ".\n";
return 0;
}
Chapter 6 Page 1
ENGG1016
Disadvantages:
1. Long program codes.
2. Easy to have typing errors.
3. Difficult to locate an error.
Functions
Chapter 6 Page 2
ENGG1016
Chapter 6 Page 3
Function
A function is a complete unit of program code for a particular task. It is used to
reduce repetitive coding and to make the whole program well structured.
Function is a way to simplify programming effort for codes of similar patterns.
Every function has a name. Parameters (arguments) are passed to the function as
an input. The function manipulates the parameters and the result (return value) is
returned to the program that calls the function.
arguments
Function(arguments)
return
value
Function Definition
A function definition consists of 2 parts: function header and function body.
The function header is divided into 3 parts:
1. Date type of return value
2. Function name
3. Data types and names of arguments
Functions
ENGG1016
// intSum4.cpp
#include <iostream>
using namespace std;
/* Calculate the same values as in intSum3.cpp using function
Advantage: Codes for calculating the sum from 1 to a positive
integer (num) is written once. Different values
are calculated by passing the integer (num) as an
argument to the function.
intSum - This is the name of the function adding all positive
integer from 1 to the integer type argument (num).
- return an integer type using keyword return
- num is the argument of the function intSum and it is
a local variable of intSum with type integer. When the
function is called, parameter is passed by copying the
value in the calling function to this local variable.
Note: 1. From the console output, please observe the sequence of
the program flow.
2. Although the functions intSum and main use the same
variable identifier (sum), these variables are local
to the corresponding function, i.e., the variable sum
is within function intSum is different from the variable
Function name
sum within main.
*/
int intSum(int num)
{
Data type and name of argument
int sum, i;
Type of
return
value
Function body
Return statement
}
int main()
{
int sum;
sum = intSum(10); // call function intSum()
cout << "Adding from 1 to 10 equals " << sum << ".\n";
sum = intSum(55); // call function intSum()
cout << "Adding from 1 to 55 equals " << sum << ".\n";
sum = intSum(125); // call function intSum()
cout << "Adding from 1 to 125 equals " << sum << ".\n";
return 0;
}
Functions
Chapter 6 Page 4
ENGG1016
Chapter 6 Page 5
intSum5.cpp works the same as intSum4.cpp but the program in the function
body of the function intSum is different.
...
n 1
n 1 n 1
nn 1
...
...
n 1
=
=
1
1 2 ... n n(n 1 )
2
// intSum5.cpp
#include <iostream>
using namespace std;
/* - Calculate the same values as in intSum4.cpp.
Note: The codes in the main functions of this program and
intSumm4.cpp are identical. However, the codes in the
functions intSum are different. That means the codes
in the function (intSum) can be modified without
changing anything in the calling function (main).
*/
int intSum(int num)
{
return (1+num) * num / 2;
Return statement.
}
The value of the expression is
returned to the calling function.
int main()
{
int sum;
sum = intSum(10); // call function intSum()
cout << "Adding from 1 to 10 equals " << sum << ".\n";
sum = intSum(55); // call function intSum()
cout << "Adding from 1 to 55 equals " << sum << ".\n";
sum = intSum(125); // call function intSum()
cout << "Adding from 1 to 125 equals " << sum << ".\n";
return 0;
}
Functions
ENGG1016
Chapter 6 Page 6
Functions
/ 2;
ENGG1016
Chapter 6 Page 7
Program Flow
Header with
#include <iostream>
const double PI = 3.1416;
void function1(void);
int function2(int i, double x);
.
.
.
preprocessor instructions
and function prototypes
int main()
1st function
{
int a, b; c;
a = 1;
b = 5;
function1( );
c = function2(1,3);
.
.
statements of
main function
void function1(void)
{
int n;
int m=3;
n = m * m * m;
.
statements
of function1
C/C++
program flow
Functions
int k, h;
h = x + 0.5;
k = i + h;
return k;
}
statements
of function2
ENGG1016
Chapter 6 Page 8
Examples
calling statement
function prototype
Void f1(void);
OK
f1( );
BAD
int y, z;
int y, z;
char c = 'A'
char c = 'A'
f2(5, c);
y = f2(z,'A');
y = f2(5,z,'B') /* number of
arguments does not match */
char get_char(void);
Functions
char c;
char c;
c = get_char( );
c = get_char('A')
ENGG1016
Chapter 6 Page 9
A function can have no argument and no return value. The warning() function in
warning.cpp is an example.
// warning.cpp
#include <iostream>
using namespace std;
/* - this is a sample function that has no argument
and no return value.
*/
void warning(void);
int main()
{
cout << "Process 1\n";
warning();
cout << "Process 2\n";
warning();
cout << "Process 3\n";
warning();
return 0;
}
void warning(void)
{
cout << "Warning!\n";
}
A function can have more than 1 argument. The mean() function in average.cpp
is an example.
// average.cpp
#include <iostream>
using namespace std;
/* - this is a sample function that have more than one arguments.
*/
double mean(double, double);
int main()
{
double num1 = 12.0, num2 = 20.0;
double num3;
num3 = mean(num1,num2);
cout << "The average value of "
<< num1 << " and " << num2
<< " is " << num3 << ".\n";
return 0;
}
double mean(double n1, double n2)
{
return ( n1 + n2 ) / 2.0;
}
Functions
ENGG1016
Chapter 6 Page 10
There is no need to assign the return value of a function to a variable. The return
value of a function can be directly used in an expression. The isEven() function in
isEvenNum.cpp is an example.
// isEvenNum.cpp
#include <iostream>
using namespace std;
bool isEven(int); // function prototype
int main()
{
int theNumber = 112;
if ( isEven(theNumber) )
cout << theNumber << " is an even number.\n";
else
cout << theNumber << " is not an even number.\n";
return 0;
}
bool isEven(int number)
{
/* if the remainder of number divided by 2 is 0,
return true. Otherwise return false */
return (number%2==0) ? true : false;
}
Functions
ENGG1016
Chapter 6 Page 11
In max.cpp, the function max() is called twice. The return value of the first call
to the function max() is passed directly as an argument to the second call to the
function max().
// max.cpp
/* find the maximum of three numbers
*/
#include <iostream>
using namespace std;
double max(double, double); // function prototype
int main()
{
double number1=3.0, number2=7.0, number3=5.0;
cout << "The maximum number of "
<< number1 << ", "
<< number2 << " and "
<< number3 << " is "
<< max(max(number1,number2),number3) << "."
<< endl;
system("PAUSE");
return 0;
}
double max(double n1, double n2)
{
return ( n1 > n2 ) ? n1 : n2;
}
Functions
ENGG1016
Chapter 6 page 12
Library Functions
The standard library has a number of functions for reuse.
The following list some commonly used standard library functions.
Function
Function Prototype
Description
Library
int abs(int);
absolute value
cstdlib (stdlib.h)
fabs
double fabs(double);
cmath (math.h)
log
double log(double);
natural logarithm
cmath (math.h)
ceil
double ceil(double);
cmath (math.h)
floor
double floor(double);
cmath (math.h)
exp
double exp(double);
cmath (math.h)
pow
cmath (math.h)
sqrt
double sqrt(double);
square root
cmath (math.h)
cos
double cos(double);
cosine
cmath (math.h)
sin
double sin(double);
sine
cmath (math.h)
tan
double tan(double);
tangent
cmath (math.h)
acos
double acos(double);
arc cosine
cmath (math.h)
asin
double asin(double);
arc sine
cmath (math.h)
atan
double atan(double);
arc tangent
cmath (math.h)
Functions
ENGG1016
Chapter 6 page 13
int isalnum(char);
cctype (ctype.h)
isalpha
int isalpha(char);
cctype (ctype.h)
isdigit
int isdigit(char);
cctype (ctype.h)
ispunct
int ispunct(char);
cctype (ctype.h)
isspace
int isspace(char);
cctype (ctype.h)
isprint
int isprint(char);
cctype (ctype.h)
islower
int islower(char);
cctype (ctype.h)
isupper
int isupper(char);
cctype (ctype.h)
tolower
int tolower(char);
cctype (ctype.h)
toupper
int toupper(char);
cctype (ctype.h)
Example
// powerN.cpp
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double number, power, result;
cout << "Please enter an integer: ";
cin >> number;
cout << "Please enter the power of an integer: ";
cin >> power;
result = pow(number,power);
cout << "The result is: " << result << endl;
return 0;
}
Functions
Chapter 5 page 14
Type conversion
Type conversion occurs when a parameter of different data type is passed to the
argument of a function.
If there is no loss in information, the compiler will automatically convert the
parameter data type into the data type of the argument.
If there is potential loss in information, warning message may be generated from
the compiler.
If the conversion does not make any sense, e.g., converting a string to an integer,
error message will be generated.
// intSum7.cpp
#include <iostream>
using namespace std;
/* Question: What happen if a parameter of different type
is passed into the argument of the function?
What about the parameter passed into the
argument is out of range? */
int intSum(int); // function prototype
int main()
{
int sum;
sum = intSum('7'); // char type is converted to int
// No warning b/c no potential data loss
// in converting char to int.
// The value of character '7' is 55
cout << "Adding from 1 to 55 equals " << sum << ".\n";
sum = intSum(55.0); // warning message from compiler
// 55.0 is converted from double to int
cout << "Adding from 1 to 55 equals " << sum << ".\n";
/* sum = intSum("55"); this statement is not valid
because string cannot be converted to int.
*/
if ( !intSum(-55) ) // function intSum used as an expression
// 0 is returned indicating error
cout << "\aError: invalid argument!\n";
return 0;
}
int intSum(int num)
{
/* further improvement in the function to check whether
the input argument is out of valid range.
If the input argument is less than 1, return 0.
*/
if (num < 1)
return 0;
return (1+num) * num / 2;
/* Can you rewrite the above statements by replacing a
single statement with conditional operator?
*/
}
Functions
Chapter 5 page 15
Overloading
The same function name can be used for functions with different number of
arguments or functions with arguments of different data types.
The compiler can differentiate which function to be used from the arguments.
Example
#include <iostream>
using namespace std;
void func(char); // function prototype of first function
void func(int); // function prototype of second function
void func(int,int); // function prototype of third function
int main()
{
func('A');
func(1);
func(1,1);
return 0;
}
void func(char ch)
3 different functions with the same name but
{
different argument data types or different number
cout << "First " << ch << endl;
of arguments
}
void func(int n)
{
cout << "Second " << n << endl;
}
void func(int n, int m)
{
cout << "Third " << n << " and " << m << endl;
}
1.
2.
3.
4.
5.
6.
// subProblem1.cpp
#include <iostream>
using namespace std;
// function prototypes
int getNumber(void);
int add(int,int,int);
double average(int,int,int);
int maximum(int,int,int);
int minimum(int,int,int);
void printResult(int,double,int,int);
int main()
{
int n1, n2, n3;
int sum, maxNum, minNum;
double aver;
//
n1
n2
n3
Chapter 5 page 16
Chapter 5 page 17
=
=
22.0 + x;
12.0 + ::x;
/* local variable
x
/* global variable x
*/
*/
Example: In the program intSum11.cpp, there are two variables named sum.
One is global and the other is a local variable in the function intSum2().
Since any function in a program can modify the value in a global variable, it is
very difficult to debug a program containing global variables. Thus, avoid using
global variable if a local variable can be used.
Functions
Chapter 5 page 18
Example
// intSum11.cpp
#include <iostream>
using namespace std;
/* A global variable is a variable defined outside any
function in the program. In this example, sum is a
global variable of type int. The functions main() and
intSum() can access to the same variable (sum) directly.
Note: The variable sum in intSum2() is a local variable
although the name is the same as the global variable.
*/
void intSum(int);
void intSum2(int);
int sum; // Global variable
int main()
{
/* the variable (sum) in the main refers to the
global variable.
*/
intSum(10);
cout << "Adding from 1 to 10 equals " << sum << ".\n";
intSum(55);
cout << "Adding from 1 to 55 equals " << sum << ".\n";
intSum(125);
cout << "Adding from 1 to 125 equals " << sum << ".\n";
intSum2(10);
cout << "Adding from 1 to 10 equals " << sum << ".\n";
intSum2(55);
cout << "Adding from 1 to 55 equals " << sum << ".\n";
intSum2(125);
cout << "Adding from 1 to 125 equals " << sum << ".\n";
return 0;
}
void intSum(int num)
{
// glocal variable (sum)
sum = (num < 1) ? 0 : (1+num) * num / 2;
}
void intSum2(int num)
{
int sum; // this is a local variable
sum = (num < 1) ? 0 : (1+num) * num / 2;
::sum = sum; // assigning global variable sum to the local variable sum
}
This is a global variable
Functions
Chapter 5 page 19
is same as
volatile int x;
volatile float y;
All static variables (keyword: static) in a function retain their values after the
function finishes execution and returns to the point where it is called. Hence the
values of all static variables may be used again when the function is called again.
Examples:
static int x;
static float y;
Example.
#include <iostream>
using namespace std;
int addN(int); // function prototype
int main()
{ int result;
result = addN(1);
cout << result << endl;
result = addN(1);
cout << result << endl;
result = addN(1);
cout << result << endl;
return 0;
}
int addN(int num)
{ static int N = 100;
N = N + num;
return N;
}
Functions
Chapter 5 page 20
Call-by-Value
When a function is called, a copy of the values of the arguments is sent to the
called function.
Any change of the arguments in the function is local to the function and will have
no effect on the values in the calling function.
Example
#include <iostream>
using namespace std;
void add10(int); // function prototype
int main()
{
int val=5;
add10(val);
cout << val << endl;
return 0;
}
void add10(int num)
{
num = num + 10;
}
Call-by-Reference
Call-by-reference is an argument-passing mechanism in which the addresses of
the variables in the calling function is copied to the called function. Through the
addresses, the called function can access the actual arguments in the calling
function enabling the called function to modify the actual argument values.
An ampersand sign & before the identifier of an argument indicates the argument
is passed by reference.
Example
#include <iostream>
using namespace std;
void add10(int&); // function prototype
int main()
{
int val=5;
add10(val);
cout << val << endl;
return 0;
}
void add10(int& num)
{
num = num + 10;
}
Functions