You are on page 1of 14

FUNCTIONS

A function is a group of statements that together perform a task. Every C++ program has at
least one function, which is main(), and all the most trivial programs can define additional
functions.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is so each function performs
a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters.
A function definition provides the actual body of the function.
A function is knows as with various names like a method or a sub-routine or a procedure etc.
Defining a Function:
The general form of a C++ function definition is as follows:
return_typefunction_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the
parts of a function:
 Return Type: A function may return a value. The return type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return type is the keyword void.
 Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters: A parameter is like a placeholder. When a function is invoked, you pass
a value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body: The function body contains a collection of statements that define
what the function does.
Example: Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum between the two:
// function returning the max between two numbers

Function compiled by [Y.A]


Page 1
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

Function Declarations:

A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source file and you call
that function in another file. In such case, you should declare the function at the top of the file
calling the function.
Calling a Function:

While creating a C++ function, you give a definition of what the function has to do. To use a
function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A
called function performs defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name,
and if function returns a value, then you can store returned value.
For example:

Function compiled by [Y.A]


Page 2
#include <iostream.h>
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout<< "Max value is : " << ret <<endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
I kept max() function along with main() function and compiled the source code. While running
final executable, it would produce the following result:
Max value is: 200

Function Arguments:

If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:

Call Type Description


Call by value This method copies the actual value of an argument into the formal parame
of the function. In this case, changes made to the parameter inside the funct
have no effect on the argument.
Call by pointer This method copies the address of an argument into the formal parame
Inside the function, the address is used to access the actual argument used
the call. This means that changes made to the parameter affect the argume

Function compiled by [Y.A]


Page 3
Call by reference This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the
actual argument used in the call. This means that changes made to
the parameter affect the argument.

Call by value

The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.
By default, C++ uses call by value to pass arguments. In general, this means that code within
a function cannot alter the arguments used to call the function. Consider the function swap()
definition as follows.
// function definition to swap the values.
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
Now, let us call the function swap() by passing actual values as in the following example:

#include<iostream.h>
#include<conio.h>
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x=y; /* put y into x */
y=temp; /* put x into y */
}
void swap(int x, int y);// function declaration
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout<< "Before swap(substitute), value of a :" << a <<endl;
cout<< "Before swap, value of b :" << b <<endl;
// calling a function to swap the values.
Function compiled by [Y.A]
Page 4
swap(a, b);
cout<< "After swap, value of a :" << a <<endl;
cout<< "After swap, value of b :" << b <<endl;
getch();
return 0;
}
When the above code is put together in a file, compiled and executed, it produces the following
result:
Before swap(substitute),, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Which shows that there is no change in the values though they had been changed inside the
function.

Call by pointer

The call by pointer method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the
actual argument used in the call. This means that changes made to the parameter affect the
passed argument.
To pass the value by pointer, argument pointers are passed to the functions just like any other
value. So accordingly you need to declare the function parameters as pointer types as in the
following function swap(), which exchanges the values of the two integer variables pointed
to by its arguments.
// function definition to swap the values.
NB: To check the more detail about C++ pointers, kindly check C++ Pointers chapter.
For now, let us call the function swap() by passing values by pointer as in the following
example:
#include<iostream.h>
#include<conio.h>
void swap(int *x, int *y); // function declaration
void swap(int *x, int *y)
{ int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */
}
int main ()
{
// local variable declaration:
Function compiled by [Y.A]
Page 5
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
getch();
return 0; }
When the above code is put together in a file, compiled and executed, it produces the following
result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

Call by reference

The call by reference method of passing arguments to a function copies the reference of an
argument into the formal parameter. Inside the function, the reference is used to access the
actual argument used in the call. This means that changes made to the parameter affect the
passed argument.
To pass the value by reference, argument reference is passed to the functions just like any
other value. So accordingly you need to declare the function parameters as reference types as
in the following function swap(), which exchanges the values of the two integer variables
pointed to by its arguments.
// function definition to swap the values.

For now, let us call the function swap() by passing values by reference as in the following
example:

#include<iostream.h>
#include<conio.h>
void swap(int&x, int&y)
{
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */

Function compiled by [Y.A]


Page 6
y = temp; /* put x into y */
return;
}
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout<< "Before swap, value of a :" << a <<endl;
cout<< "Before swap, value of b :" << b <<endl;
/* calling a function to swap the values using variable reference.*/
swap(a, b);
cout<< "After swap, value of a :" << a <<endl;
cout<< "After swap, value of b :" << b <<endl;
getch();
return 0;
}
When the above code is put together in a file, compiled and executed, it produces the following
result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :50
After swap, value of b :60
By default, C++ uses call by value to pass arguments. In general, this means that code within
a function cannot alter the arguments used to call the function and above mentioned example
while calling max() function used the same method.

Default arguments and function overloading


Default Values for Parameters (Default arguments)

When you define a function, you can specify a default value for each of the last parameters.
This value will be used if the corresponding argument is left blank when calling to the
function.
This is done by using the assignment operator and assigning values for the arguments in
the function definition. If a value for that parameter is not passed when the function is
called, the default given value is used, but if a value is specified this default value is
ignored and the passed value is used instead. E.g.: Let us develop part of the program
with default arguments.

Function compiled by [Y.A]


Page 7
#include<iostream.h>
#include<conio.h>
void Add_Display(int x=10, int y=20, int z=30)
{
cout<< (x+y+z)<<endl;
}
void Mult_Dispaly(long int x,long int y=70,long int z=90)
{
cout<< (x*y*z)<<endl;
}
void MIN_Display(int x,int y,int z=4)
{
cout<< (x-y-z)<<endl;
}
void main()
{
int a=40, b=50, c=60;
Add_Display(a,b,c); //will print 150 (ie 40+50+60)
Add_Display(a,b); //will print 120 (ie 40+50+30)
Add_Display(a); //will print 90 (ie 40+20+30)
Add_Display(); //will print 60 (ie 10+20+30)
Mult_Dispaly(a,b,c); //will print 120000 (40*50*60)
Mult_Dispaly(a,b); //will print 180000 (40*50*90)
Mult_Dispaly(b); //will print 315000 (50*70*90) etc...
MIN_Display(a,b,c);
MIN_Display(a,b);
MIN_Display(c,b,5);//will print 5(60-50-5)
getch();
}

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.
When the above code is compiled and executed, it produces the following result:
#include<iostream.h>
#include<conio.h>
int manip(int);
int manip(int, int);
int manip(int, double);
int main()

Function compiled by [Y.A]


Page 8
{
int x = 2, y= 4, z;
double a = 3.1;
z = manip(x) + manip(x, y) + manip(y, a);
int m,n,k;
m= manip(x);
n= manip(x,y);
k= manip(y,a);
cout<<"\nFirst fun: "<<m;
cout<<"\nSecond fun:"<<n;
cout<<"\nThird fun: "<<k;
cout<<"\nTOTAL OF ALL OVERLOAD:"<< z << endl;
getch();
return 0;
}
int manip(int val)
{
return val + val * 2;
}
int manip(int val1, int val2)
{
return (val1 + val2) * 2;
}
int manip(int val1, double val2)
{
return val1 * val2;

Recursion versus Iteration


Both iteration and recursion are based on control structure. Iteration uses a repetition structure
(such as for, while, do…while) and recursive uses a selection structure (if, if else or switch).
Both iteration and recursive can execute infinitely-an infinite loop occurs with iteration if the
loop continuation test become false and infinite recursion occurs id the recursion step doesn’t
reduce the problem in a manner that coverage on a base case.
Recursion has disadvantage as well. It repeatedly invokes the mechanism, and consequently
the overhead of method calls. This can be costly in both processor time and memory space.
Each recursive call creates another copy of the method (actually, only the function’s
variables); this consumes considerable memory.

Function compiled by [Y.A]


Page 9
N.B: Use recursion if:
 A recursive solution is natural and easy to understand
 A recursive solution doesn’t result in excessive duplicate computation.
 The equivalent iterative solution is too complex and
 of course, when you are asked to use one in the exam!!

Example:
n
The following code fragment computes the exponentiation A 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);
}

#include<iostream.h>
float expo(float A, int N)
{
if(N==1)
return A;
else
return A * expo(A,N-1);
}
main()
{
int s=2,a=4;
cout<<expo(s,a);
return 0;
}

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.

Function compiled by [Y.A]


Page 10
- Factorial of a positive number n is n time the factorial of n-1.
- The second line clearly indicates that factorial is defined in terms of itself and
hence can be expressed as a recursive function.

C++ Program to Find Factorial of a Number using recursion

#include<iostream>
using namespace std;
int factorial(unsigned int n);
int main()
{
unsigned int e;
cout << "Enter a positive integer: ";
cin >> e;
cout << "Factorial of " << e << " = " << factorial(e);
return 0;
}
int factorial(unsigned int n)
{
if(n > 1)
return n * factorial(n - 1);
else
return 1;}

For n set to 4, the following figure shows the recursive call:

The stack frames for these calls appear sequentially on the runtime stack, one after the other.
Function compiled by [Y.A]
Page 11
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

Exercise: C++ Program to Find Factorial of a Number using Iteration

Iterative is just calculating it inside a loop of some kind, i.e. iterating one at a time
until you arrive to your answer. This is the more "natural" way of doing it. This is
how you do it on paper.
#include<iostream>
using namespace std;
fact_iter(int n)
{
int result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}
int main()
{
int n;
while (1)
{
cout<<"Enter interger to compute factorial(0 to exit): ";
cin>>n;
if (n == 0)
break;
cout<<fact_iter(n)<<endl;
}
return 0;
}

Function compiled by [Y.A]


Page 12
Math Operations in C++:

In addition to the various functions you can create, C++ also includes some useful functions
you can use. These functions are available in standard C and C++ libraries and called built-
in functions. These are functions that can be included in your program and then use.
C++ has a rich set of mathematical operations, which can be performed on various numbers.
Following table lists down some useful built-in mathematical functions available in C++.
To utilize these functions you need to include the math header file <cmath>.

S.N. Function & Purpose


1 doublecos(double); This function takes an angle (as a double) and returns the cosine.
2 double sin(double); This function takes an angle (as a double) and returns the sine.
3 double tan(double); This function takes an angle (as a double) and returns the tangent.
4 double log(double); This function takes a number and returns the natural log of that
number.
5 double pow(double, double); The first is a number you wish to raise and the second is
the power you wish to raise it to.
6 doublehypot(double, double); If you pass this function the length of two sides of a right
triangle, it will return you the length of the hypotenuse.
7 doublesqrt(double); You pass this function a number and it gives you this square root.
8 int abs(int); This function returns the absolute value of an integer that is passed to it.
9 doublefabs(double); This function returns the absolute value of any decimal number
passed to it.
10 double floor(double); Finds the integer which is less than or equal to the argument
passed to it.

Following a simple example to show few of the mathematical operations:

#include<iostream.h>
#include<conio.h>
#include<math.h>
int main ()
{
// number definition:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// mathematical operations;
cout<< "sin(d) :" << sin(d) <<endl;
cout<< "abs(i) :" << abs(i) <<endl;
cout<< "floor(d) :" << floor(d) <<endl;

Function compiled by [Y.A]


Page 13
cout<< "sqrt(f) :" <<sqrt(f) <<endl;
cout<< "pow( d, 2) :" << pow(d, 2) <<endl;
cout<< "absolute of(s) :" << abs(s) <<endl;
getch();
return 0;
}
When the above code is compiled and executed, it produces the following result:
sign(d) :-0.634939
abs(i) :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
absolute of(s): 10

Random Numbers in C++:

There are many cases where you will wish to generate a random number. There are actually
two functions you will need to know about random number generation. The first is rand(),
this function will only return a pseudo random number. The way to fix this is to first call the
srand() function.
Following is a simple example to generate few random numbers. This example makes use of
time() function to get the number of seconds on your system time, to randomly seed the rand()
function:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h> //for ramdom function
int main ()
{
int i,j;
// set the seed
/* generate 10 random numbers. */
for(i = 0; i< 10; i++ )
{
// generate actual random number
j= rand();
cout<<" Random Number : " << j <<endl;
}
getch();
return 0;
}

Function compiled by [Y.A]


Page 14

You might also like