Chapter 4- Functions
Chapter 4- Functions
CHAPTER FOUR
FUNCTIONS
INTRODUCTION
What is function?
A function is defined as a group of instruction used to achieve a specific task. These functions
can be called from other function. Hence if any groups of statements are to be frequently used
then the statements are grouped together and named which is accessed by that new function
when needed.
Functions decrease the complexity of a program. A program having multiple functions can be
easily debugged than a program that is large and runs without a single function. So a function
reduces the size of a program and increases the program modularity.
C++ adopts functions as its fundamental programming approach .Basics of C++ deals more
with functions and even classes also use the functions as their member functions.
Advantages of functions
Increase program modularity
Reduction in the amount of work & development time
Program and function debugging is easier
Division of work is simplified
Reduction in the size of the program due to code reusability
Functions can be accessed repeatedly without redevelopment, which in turn promotes
reuse of code
TYPES OF FUNCTION
Functions are of two types:
Library/built-in function
User defined function
1. Library/Built-in function
Library functions are pre-written functions or built in functions. Many activities in C++ use
library functions. These functions include graphical functions, text formatting functions,
memory management and data conversion.
Some of the mathematical functions available in the C++ mathematics library are listed below:
acos(x) inverse cosine, -1 <= x <= +1, returns value in radians in range 0 to PI
asin(x) inverse sine, -1 <= x <= +1, returns value in radians in range 0 to PI
Consider the following example which uses ceil and floor library functions from math.h. The
floor function rounds up the float value to the nearest lower integer where as ceil rounds up
the float value to the nearest upper integer.
Example:
Output
#include<math.h>
#include<iostream.h>
int main()
float number=255.98;
float down,up;
down=floor(number);
up=ceil(number);
return 0;
Besides the library functions, we can also define our own functions which are called as user
defined functions. C++ allows declaring user-defined functions, which reduces program size
and increase modularity.
Example:
#include<iostream.h>
Output
void func(); //Function declaration
void main()
func();//Function calling
void func()
Just like a variable has to be declared before using, a function also has to be declared.
The statement just above the main is the function declaration. A function declaration tells the
compiler that at some later point we are going to use a function by that name. It is called as
prototype declaration. It should be terminated because it acts like a single statement.
Declaring function:
o The interface of a function (also called its prototype) specifies how it may be used. It consists of
three entities:
o The function return type. This specifies the type of value the function returns. A function which
returns nothing should have a return type void.
o The function name. this is simply a unique identifier
o The function parameters (also called its signature). This is a set of zero or more typed identifiers
used for passing values to and from the function.
Defining a function:
o A function definition consists of two parts: interface (prototype) & body. The brace of a function
contains the computational steps (statements) that computerize the function. The definition
consists of a line called the decelerator.
o If function definition is done before the main function, then there is no need to put the prototype,
otherwise the prototype should be scripted before the main function starts.
void main()
---------------
---------------
--------------
} no semicolon.
#include<conio.h>
int main()
starLine();
starLine();
return 0;
void starLine()
cout<<endl;
Given the next program, which function is the calling function and which is the called
function?
#include<iostream.h>
#include<conio.h>
void nextMsg();
int main()
cout<< “Hello!\n”;
nextMsg();
return 0;
void nextMsg()
cout<< “GoodBye!\n”;
return;
Function Return
Functions can be grouped into two categories: functions that do not have a return value
(void function) and functions that have a return value.
The return statement in a function need not at the end of the function. It can occur
anywhere in the function body and as soon as it is countered, execution control will be
returned to the caller.
Caller called
A function can also have arguments. An argument is a piece of data passed from a program to
a function. The arguments are the variables that are passed in the parenthesis of a function.
These arguments are used to process the data sent by the program.
Syntax:
void myfunc(int,int);
This specifies the function called myfunc that takes two integer variables as arguments. A
compiler identifies a function with the number of arguments and type of arguments other-
wise which raises a compiler error. When we are declaring functions, the variables in function
declaration are known as parameters. During function execution they are known as function
arguments.
Example:
#include<iostream.h>
void main()
{
Output
int x,y;//declares two integer variables
cin>>x;
cin>>y;
cout<<”x+y=”<<a+b<<endl;
cout<<”x-y=”<<a-b<<endl;
cout<<”x*y=”<<a*b<<endl;
cout<<”x/y=”<<a/b<<endl;
The program accepts two integer variables and passes them as arguments to the function
disp. The disp function performs all the arithmetic operations on them and displays the
result.
Sometimes it becomes necessary that a program passing arguments expecting a return from
the function. This is known as arguments with return value. Actually when you declare a
function as void it implies that the function need not return anything.
This means that if you don’t specify void before the function name, the calling function is
expecting a return from the called function.
The return may be an int variable or a char variable or any other variable of any type. In this
case a function that returns a value should be specified before the function at the time of
declaration and definition.
Example:
The program defines a function called power, which takes two integer variables and prints
the power of the first number raised to second number. Finally after calculating power the
value is returned to the calling function. You will observe that in place of void before the
function name it is given as int so that it will return a value of int.
#include<iostream.h>
void main()
int a,b,c;
Page 9 of 18 Department of Computer Science & Technology
Compiled by: Wubet N. (meetwubet@gmail)
Fundamentals of Programming Chapter Four: Functions
cin>>a;
cin>>b;
int p=1;
while(j>0)
p=p*i;
j--;
From the above program it is understood that, to make a function to return a value, the type
has to be specified before the function name.
Call by value can return the result of a calculation. But it cannot affect the original
variables. That is, in call by value the variables that are passed with as arguments from the
caller function gets copied into the variables that are defined with the function definition. So
the copies of the original variables are created at another memory location. Thus the changes
to these variables are not affected to original variables.
Sometimes it is necessary to change the values of original variables that have been passed in
the caller function. We can achieve this using call by reference.
In call by reference, the address of the variables passes as arguments to the function. Thus the
variables which are defined along with the function definition can actually access the values
of the variables that are being passed to the function to the caller function. And hence the
alteration for the original variables is possible.
Example:
#include<iostream.h>
int swap(int &,int &);//& indicates you are passing the addresses of the values not the
values
void main()
{
int a=10;
int b=90;
swap(a,b);//values of a and b are passed to the function
cout<<”The values of a is:”<<a<<endl;
cout<<”The value of b is: <<b<<endl; Output
} The value of a is: 90
{
int temp;
temp=p;
p=q;
q=temp;
return 0;
}
In the example shown above you passed the address of the variables as argument. You will
find that the declaration of swap included an & specified in place of arguments. It means that
the function is expecting addresses of the variables as arguments.
Page 11 of 18 Department of Computer Science & Technology
Compiled by: Wubet N. (meetwubet@gmail)
Fundamentals of Programming Chapter Four: Functions
& is called “address of” operator. It is used to pass the address of a variable to the called
function or variable. So the variable declared in definition of function also gets created at the
same address. It implies that the variables can access the value of original variables. Thus
they can be altered. So call by reference works fine when it is needed to access the original
variables not created a copy of it.
Arrays as parameters
At some moment we may need to pass an array to a function as a parameter. In C++ it is not
possible to pass by value a complete block of memory as a parameter, even if it is ordered as an
array, to a function, but it is allowed to pass its address, which has almost the same practical
effect and is a much faster and more efficient operation.
In order to admit arrays as parameters the only thing that we must do when declaring the
function is to specify in the argument the base type for the array that it contains, an identifier
and a pair of void brackets [] . For example, the following function:
admits a parameter of type "Array of int " called arg . In order to pass to this function an array
declared as:
procedure (myarray);
#include <iostream.h>
#include <conio.h>
void main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
mult(firstarray,3);
printarray (firstarray,3);
getch()
}
As you can see, the first argument (int arg[] ) admits any array of type int , whatever its
length is, for that reason we have included a second parameter that informs the function
the length of each array that we pass to it as the first parameter so that the for loop that
prints out the array can have the information about the size we are interested about. The
function mult doubles the value of each element and the firstarray is passed to it. After
that the display function is called. The output is modified showing that arrays are passed
by reference.
To pass an array by value, pass each element to the function
Example:
int xyz;//xyz is global
void Foo(int xyz)//xyz is local to the body of Foo
{
if(xyz > 0)
{
Double xyz;//xyz is local to this block
…
}
}
Scope Operator
Because a local scope overrides the global scope, having a local variable with the same name as a
global variable makes the latter inaccessible to the local scope.
Eg
int num1;
void fun1(int num1)
{
//…
}
The global num1 is inaccessible inside fun1(), because it is overridden by the local num1
parameter.
This problem is overcome using the scope operator ‘::’ which takes a global entity as argument.
int num1 = 2;
void fun1(int num1)
{
//…
num1=33;
cout<<num1; // the output will be 33
cout<<::num1; //the output will be 2 which is the global
if(::num1 != 0)//refers to global num1
//…
The opposite of an automatic is a static variable. All global variables are static and, as
mentioned, all static variables retain their values. Therefore, if a local variable is static, it
too retains its value when its function ends-in case this function is called a second time.
To declare a variable as static, place the static keyword in front of the variable when you
define it. The following code section defines three variables i, j, k. the variable i is
automatic, but j and k are static.
Static variables can be declared and initialized within the function, but the initialization
will be executed only once during the first call.
If static variables are not declared explicitly, they will be declared to 0 automatically.
Eg. void my_fun()
{
static int num;
static int count = 2;
count=count*5;
num=num+4;
}
In the above example:
o During the first call of the function my_fun(), the static variable count will be initialized to 2
and will be multiplied by 5 at line three to have the value 10. During the second call of the same
function count will have 10 and will be multiplied by 5.
o During the first call of the function my_fun(), the static variable num will be initialized to 0 (as
it is not explicitly initialized) and 4 will be added to it at line four to have the value 4. During
the second call of the same function num will have 4 and 4 will be add to it again.
N.B. if local variables are static, their values remain in case the function is called again.
b. Overloaded Functions
Unlike C, C++ lets you have more than one function with the same name. In other
words, you can have three functions called abs() in the same program.
Functions with the same name are called overloaded functions. C++ requires that each
overloaded functions differ in its argument list. Overloaded functions enable you to
have similar functions that work on different types of data.
Suppose that you wrote a function that returned the absolute value of whatever
number you passed to it:
int iabs(int i)
{ if(i<0)
return (i*-1);
else
return (i);
}
float fabs(float x)
{ if(x<0.0)
return (x * -1.0);
else
return (x);
}
float abs(flaot x)
{
if(x<0.0)
return x*-1.0;
else
return x;
}
N.B: if two or more functions differ only in their return types, C++ can’t overload
them. Two or more functions that differ only in their return types must have different
names and can’t be overloaded
c. Recursion
A function which calls itself is said to be recursive. Recursion is a general programming
technique applicable to problems which can be defined in terms of themselves. Take the
factorial problem, for instance which is defined as:
- factorial of 0 is 1
The second line clearly indicates that factorial is defined in terms of itself and hence can
be expressed as a recursive function.
int Factorial(unsigned int n )
{
return n = = 0 ? 1 : n * factrial(n-1);
}
For n set to 4, the following figure shows the recursive call:
Factorial(4)
24
4 * Factorial(3)
6 3 * Factorial(2)
2 2* Factorial(1)
1 1
The stack frames for these calls appear sequentially on the runtime stack, one after the
other.
A recursive function must have at least one termination condition which can be satisfied.
Otherwise, the function will call itself indefinitely until the runtime stack overflows.
The three necessary components in a recursive method are:
1. A test to stop or continue the recursion
2. An end case that terminates the recursion
3. A recursive call(s) that continues the recursion
let us implement two more mathematical functions using recursion
e.g the following function computes the sum of the first N positive integers 1,2,…,N.
Notice how the function includes the three necessary components of a recursive method.
int sum(int N)
{
if(N==1)
return 1;
else
return N+sum(N);
}
The last method computes the exponentiation An where A is a real number and N is a
positive integer. This time, we have to pass two arguments. A and N. the value of A will
not change in the calls, but the value of N is decremented after each recursive call.
float expo(float A, int N)
{
if(N==1)
return A;
else
return A * expo(A,N-1);
}
Worksheet 4.
1. Write an int function cube () that returns the cube of its single int formal parameter.
2. Write a float function triangle() that computes the area of a triangle using its two formal
parameters h and w, where h is the height and w is the length of the bases of the
triangle.
3. Write a float function rectangle() that computes and returns the area of a rectangle
using its two float formal parameters h and w, where h is the height and w is the width
of the rectangle.
4. Write a program that accepts a positive integer from the user and displays the factorial
of the given number. You should use a recursive function called factorial() to calculate
the factorial of the number.
5. Write a function called isPrime() that accepts a number and determine whether the
number is prime or not.
6. Write a function called isEven() that uses the remainder operator(%) to determine
whether an integer is even or not.