You are on page 1of 20

ENGG1016

Chapter 6

Computer Programming and Applications

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

Solve the same problem using a for-loop.


// intSum2.cpp
#include <iostream>
using namespace std;
/* - for loop is used replacing the long line in intSum1.cpp
- while loop or do-while loop can also be used.
Advantage: Codes are shorter. If the sum to a larger
number is calculate (e.g. 20) only need to replace
the number 10 in the for-loop by 20. This reduce the
chance of typing error.
*/
int main()
{
int sum, i;
sum = 0; // reset sum to zero
for (i=1; i<=10; i++) // loop from 1 to 10
sum += i;
cout << "Adding from 1 to 10 equals " << sum << ".\n";
return 0;
}
Functions

Chapter 6 Page 1

ENGG1016

Computer Programming and Applications

More similar calculations:


- add all integers from 1 to 10,
- add all integers from 1 to 55 and
- add all integers from 1 to 125,
Copy and paste the codes of the for-loop in intSum2.cpp.
// intSum3.cpp
#include <iostream>
using namespace std;
/* To calculate three values:
1. add all integers from 1 to 10.
2. add all integers from 1 to 55.
3. add all integers from 1 to 125.
Problem: Is it necessary to repeat similar codes if more
sums are calculated?
*/
int main()
{
int sum, i;
sum = 0; // reset sum to zero
for (i=1; i<=10; i++) // loop from 1 to 10
sum += i;
cout << "Adding from 1 to 10 equals " << sum << ".\n";
sum = 0; // reset sum to zero
for (i=1; i<=55; i++) // loop from 1 to 55
sum += i;
cout << "Adding from 1 to 55 equals " << sum << ".\n";
sum = 0; // reset sum to zero
for (i=1; i<=125; i++) // loop from 1 to 125
sum += i;
cout << "Adding from 1 to 125 equals " << sum << ".\n";
return 0;
}

Disadvantages:
1. Long program codes.
2. Easy to have typing errors.
3. Difficult to locate an error.

Functions

Chapter 6 Page 2

ENGG1016

Computer Programming and Applications

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

In the function body, program is written to manipulate the arguments.


The last statement of execution in the function must be a return statement.
A return statement consists of the keyword return followed by an expression.
The value of the expression in the return statement will be returned to the calling
function as the result of the function.
Example: intSum4.cpp works the same as the program intSum3.cpp. In
intSum4.cpp, a function, named intSum, is defined to replace all repeated codes
in intSum3.cpp.

Functions

ENGG1016

Computer Programming and Applications

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

sum = 0; // reset sum to zero


for (i=1; i<=num; i++) // loop from 1 to num
sum += i;
cout << sum << endl;
return sum;

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

Computer Programming and Applications

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

Computer Programming and Applications

Chapter 6 Page 6

Function Declaration (prototype)


Before a function is called, the function is either defined or declared.
In the programs intSum4.cpp and intSum5.cpp, the function definition of
intSum must be placed in the program file in a position higher than the main
function in the program. Thus, the compiler can read the definition of the function
intSum before it can be used in main.
Alternatively, the declaration of the function (or the function prototype) can be
placed at the top position of the program file, i.e., at a position higher than the
main. Function definition can then be placed anywhere in the file.
Function declaration consists of three parts:
1. the type of return value
2. the function name
3. the type of the argument(s)
Program intSum6.cpp works the same as program intSum5.cpp but function
prototype is used.
// intSum6.cpp
#include <iostream>
using namespace std;
/* Similar to intSum5.cpp but function declaration is used. Once a function
is declared, the function can be used by codes in the remaining part of
the program. The function can, then, be defined anywhere in the program.
*/
int intSum(int);
/* function prototype / declaration can also be written
in following way: int intSum(int num);
*/
int main()
{
int sum;
sum = intSum(10);
cout << "Adding from
sum = intSum(55);
cout << "Adding from
sum = intSum(125);
cout << "Adding from
return 0;
}
int intSum(int num)
{
return (1+num) * num
}

Functions

1 to 10 equals " << sum << ".\n";


1 to 55 equals " << sum << ".\n";
1 to 125 equals " << sum << ".\n";

/ 2;

ENGG1016

Computer Programming and Applications

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

main is always the

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

int function2(int i, double x)


{

C/C++
program flow

Functions

int k, h;
h = x + 0.5;
k = i + h;
return k;
}

statements
of function2

ENGG1016

Computer Programming and Applications

Chapter 6 Page 8

Calling Functions and Passing Arguments


The statement to call a function is the name of the function.
If the function has a return value, such a value may be assigned in the call
statement to a variable of the same data type.
If the function expects some arguments, the call statement must provide
corresponding number and data types of arguments as declared in the function
prototype.
The names of the arguments (variables) in the call statement may be different
from those declared in the prototype. In fact, only the values (not the names) of
the arguments are copied and passed to the function. Hence any subsequent
changes to these arguments in the function will be LOCAL, i.e., the changes will
be confined to the function itself and will not affect other areas, such as the main( )
or where the function is called.

Examples
calling statement
function prototype
Void f1(void);

OK

f1( );

BAD

k = f1(5); /* no return value


and no argument expected */

int f2(int x, char c);

int y, z;

int y, z;

char c = 'A'

char c = 'A'

f2(5, c);

f2(c,5); /* wrong data type*/

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

Computer Programming and Applications

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

Computer Programming and Applications

Chapter 6 Page 10

Instead of passing values of variables to a function, values of expressions can also


be passed. The parameter passed to the function circleArea() is an example of
passing an expression to a function.
// circleArea.cpp
#include <iostream>
using namespace std;
double circleArea(double); // function prototype
int main()
{
double circumference, area;
circumference = 1.0;
area = circleArea(circumference/(2.0*3.14159)); // this is an expression
cout << "The area of circle with circumference "
<< circumference << " is " << area << endl;
return 0;
}
double circleArea(double radius)
{
return 3.14159 * radius * radius;
}

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

Computer Programming and Applications

Chapter 6 Page 11

The return value of a function can also be used directly as an argument of a


function. The return value of the function radius() in circleArea2.cpp is directly
passed as an argument to the function circleArea().
// circleArea2.cpp
#include <iostream>
using namespace std;
double circleArea(double); // function prototype
double radius(double);
int main()
{
double circumference, area;
circumference = 1.0;
area = circleArea(radius(circumference));
cout << "The area of circle with circumference "
<< circumference << " is " << area << ".\n";
return 0;
}
double radius(double c)
{
return c/(2.0*3.14159);
}
double circleArea(double r)
{
return 3.14159 * r * r;
}

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

Computer Programming and Applications

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

Mathematical Library Functions


abs

int abs(int);

absolute value

cstdlib (stdlib.h)

fabs

double fabs(double);

absolute value for floating-point numbers

cmath (math.h)

log

double log(double);

natural logarithm

cmath (math.h)

ceil

double ceil(double);

the smallest integral value not less than a given value

cmath (math.h)

floor

double floor(double);

the largest integral value not greater than a given value

cmath (math.h)

exp

double exp(double);

"e" raised to a given power

cmath (math.h)

pow

double pow(double, double);

the first argument raised to the power of the second argument

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

Computer Programming and Applications

Chapter 6 page 13

Character Library Functions


isalnum

int isalnum(char);

return non-zero if a character is alphanumeric

cctype (ctype.h)

isalpha

int isalpha(char);

return non-zero if a character is alphabetic

cctype (ctype.h)

isdigit

int isdigit(char);

return non-zero if a character is a digit

cctype (ctype.h)

ispunct

int ispunct(char);

return non-zero if a character is punctuation

cctype (ctype.h)

isspace

int isspace(char);

return non-zero if a character is a white space character

cctype (ctype.h)

isprint

int isprint(char);

return non-zero if a character is a printing character

cctype (ctype.h)

islower

int islower(char);

return non-zero if a character is lowercase

cctype (ctype.h)

isupper

int isupper(char);

return non-zero if a character is an uppercase character

cctype (ctype.h)

tolower

int tolower(char);

converts a character to lowercase

cctype (ctype.h)

toupper

int toupper(char);

converts a character to uppercase

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

ENGG1013/ENGG1014 Computer Programming and Applications

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

ENGG1013/ENGG1014 Computer Programming and Applications

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

Function Calling other Function


A complex problem, which cannot be easily implemented within a few statements,
can be broken down into sub-problems. Each sub-problem is implemented by a
function.
If a sub-problem is still too complex, it can also be further broken down into
sub-problems and implemented in functions.
The use of functions facilitates stepwise design of programs in problem-solving.
Example: subProblem1.cpp.
The problem:
Ask the user to enter three integers. Calculate the sum, average, maximum
and minimum values of the integers and then display the calculation results to
the console.
Sub-problem:
Functions

ENGG1013/ENGG1014 Computer Programming and Applications

1.
2.
3.
4.
5.
6.

Ask the use to enter an integer


Calculate the sum of three integers
Calculate the average of three integers
Calculate the maximum of three integers
Calculate the minimum of three integers
Display the calculation results to the console.

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

get data: n1, n2, n3


= getNumber();
= getNumber();
= getNumber();

// calculations: sum, average, maximum and minimum


sum = add(n1,n2,n3);
aver = average(n1,n2,n3);
maxNum = maximum(n1,n2,n3);
minNum = minimum(n1,n2,n3);
// report result
printResult(sum,aver,maxNum,minNum);
return 0;
}
int getNumber(void)
{
int n;
cout << "Please enter an integer: ";
cin >> n;
return n;
}
int add(int num1,int num2,int num3)
{
return num1 + num2 + num3;
}
double average(int num1,int num2,int num3)
{
return (num1+num2+num3)/3.0;
}
Functions

Chapter 5 page 16

ENGG1013/ENGG1014 Computer Programming and Applications

Chapter 5 page 17

int maximum(int num1,int num2,int num3)


{
if ( num1 >= num2 && num1 >= num3 )
return num1;
else if ( num2 >= num3 )
return num2;
else
return num3;
}
int minimum(int num1,int num2,int num3)
{
if ( num1 <= num2 && num1 <= num3 )
return num1;
else if ( num2 <= num3 )
return num2;
else
return num3;
}
void printResult(int in1, double in2, int in3,int in4)
{
cout << "The sum is: " << in1 << endl;
cout << "The average value is: " << in2 << endl;
cout << "The maximum is: " << in3 << endl;
cout << "The minimum is: " << in4 << endl;
}

Local / Global Variables


A variable declared outside a function (normally before main( ) ) is referred to as
global variable. A global variable may be accessed by all functions, subsequent
to the declaration of the variable, in the program.
A variable declared inside a function is called a local variable. A local variable
may only be accessed by the function in which it is defined.
If the name of a local variable in a function is same as that of a global variable,
the global variable is hidden by the local variable. The hidden global variable
may be accessed by the scope operator :: , e.g.,
z
y

=
=

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

ENGG1013/ENGG1014 Computer Programming and Applications

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

This is a local variable

ENGG1013/ENGG1014 Computer Programming and Applications

Chapter 5 page 19

Volatile / Static Variables


All volatile variables (keyword: volatile) in a function disappear when the
function finishes execution and returns to the point where it is called.
All variables by default are volatile, i.e,
int x;
float y;

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

ENGG1013/ENGG1014 Computer Programming and Applications

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

You might also like