Chapter 5
Function in C++
1
What is function?
A function is a block of statements that performs a
specific task.
A c++ program is written by combining new functions
with “prepackaged” functions available in C++ Standard
Libraries.
Functions allow you to modularize a program by
separating its tasks into self-contained units.
Every C++ program has at least one function which is
named by main() .
Every C++ function starts execution from main function.
2
Types of function
There are two types of functions:
I.User defined functions:-functions written by user or
programmer are referred to as user-defined or programmer-
defined functions.
II.Built-in functions( standard C++ library
functions)are a collection of pre-defined functions and
other program elements which are accessed through header
files.
•Its actual code is hidden away within the Standard C++
Library.
3
User defined function
User Defined Functions appear in programs
in 3 ways:
1. Functions have to be implemented (defined)
2. Just like variables, functions have be declared
before they can be used (called)
3. Functions have to be invoked or called.
4
1.Function Definition
A function definition provides the body of the
function that performs its actual work.
It consists of function header and function
body
5
General format of function(General syntax of
function defination)
Function Header
Return_Type function_name(Parameter1, Parameter2,…)
{
//statements ;
1. Return type 3. Parameter
2. Function Name 4. Body
Basically function consists of theses 4 things
6
Return type
The return type is the data type of the value that the
function returns such as int, float, string etc…
Some functions perform the desired operations without
returning a value. In this case, the return type is the
keyword void.
Void return type is:-used when, We do not need the
function to return any value.
Using void is a signal to the compiler that no value will be
returned 7
Return Values
The keyword return in a function has two jobs:
• To form the return value of the function.
• To finalize the function.
After the keyword return , a variable, a constant, an expression
or a function can be placed.
Example:-return 5;
return a+b;
A function may contain more than one return statement.
However, the function is finalized after the first encounter of a
return statement.
8
Function name
Is a valid C++ identifier given to name of the function. The function
name and the parameter list together constitute the function signature.
Function Parameter
Parameters are list of input argument(a value provided to the
function to obtain the function’s result).
When a function is invoked(called), you pass a value to the
parameter.
The parameter list refers to the Data type, order, and number of
the parameters of a function.
Parameters are optional; that is, a function may or may not
contains parameters. 9
Function body
The function body contains a block or a collection of
statements that define what the function does.
A statement inside body of the function are executing
when the function is invoked /called.
Inside body of a function we can use blocks of control
structures, variable initiation, declaration of local
variable cin and cout statement and other function
calling etc…
10
2. Function declaration( prototype )
Proper function prototype format (declaration syntax)
Return_type func_name(type p1, type p2,..);
A function declaration tells the compiler about a function
name, return type, lists of type of parameters and how to
call a function.
The actual body of the function can be defined separately.
The function prototype or declaration is a statement,
which ends with a semicolon.
11
Parameter names are optional in function declaration/prototype
only their type is required, so following is also valid declaration:
Return_type func_name(type,type,…);
Example of prototype
Type
int max(int,int);
Return type Function Nam Parameters
int max(int x,int y);
12
Function Prototype Examples
long FindArea(long length, long width);// returns long, has two
parameters
void PrintMessage(int messageNumber); // returns void,
has one parameter
int GetChoice(); // returns int, has no
parameters
goodFunction(); // returns int, has no
parameters
13
Why function prototype/ Declaration?
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.
A function body can also be written after main() function.
In this case, a function prototype has to be given before
main().
We can omit function declaration or prototype if we
define the main function bellow all other function .
14
3.Function calling
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
caller function.
To call a function you need to pass the required parameters along
with function name and if function returns a value then you can
store returned value in variable with appropriate data type .
Calling syntax:
Function_Name(parametr1,parametr2,…) ;
15
Example of using function
#include<iostream>
using namespace std;
Function prototype
int sum(int, int);
int main ()
{
int s; Function calling
s = sum(22, 33);
cout << "The sum is " << s << endl;
return 0;
Function definition
}
int sum (int a, int b)
{
int c;
c = a + b;//22+33=55
return c;
}
16
Function Arguments
The actual value that passes to parameter of function
definition from the calling function is called argument.
Data type of an argument from the calling function should
match with data type of a parameter in function definition
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 or end of the function.
17
Argument passing
While calling a function, there are two ways that arguments can be
passed to a function:
• Argument pass by value
• Argument pass by Reference
Argument pass by value
This method copies the actual value of an argument into the formal
parameter of the function.
Changes made to the parameter inside the function have no effect on
the argument.
By default, C++ uses pass by value to pass arguments.
18
Argument Pass by reference
This method 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 changes made to the
parameter affect the argument.
With pass-by-reference, the caller gives the called function
• the ability to access the caller’s data directly, and
• the ability to modify that data.
Pass by reference uses an ampersand sign (&) in between the data
type and variable name such as:
int swap(int & x, int & y);
19
Example on Argument Passing by value
#include<iostream>
using namespace std;
int add(int x);
int main()
{
int number, result;
number=5;
cout << " The initial value of number is " << number << endl;
result=add(number); //add(5)
cout << " The final value of number is " << number << endl;
cout << " The result is : " << result << endl;
return(0);
}
int add(int x)
{
x=x+100;
return(x);
} 20
Example on Argument Passing by Reference
#include<iostream>
Void duplicate( int &a, int &b, int &c)
{
a*=2;
b*=2;
c*=2;
}
int main()
{
int x=1,y=3,z=7;
duplicate(x,y,z);
cout<<"x="<<x<<" "<<"y="<<y<<" "<<"z="<<z;
return 0;
} 21
Default Values for Parameters
When you define a function you can specify a
default value for each of parameters.
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
22
#include <iostream> Example of default value of parameter
using namespace std;
int sum(int a, int b=20)
{
int result;
result = a + b;
return (result);
}
int main ()
{
int a = 100, b = 200, result;
result = sum(a, b);
cout << "Total value is :" << result << endl;
result = sum(a);
cout << "Total value is :" << result << endl;
return 0;
} 23
Once we provide a default value for a parameter, all
subsequent parameters must also have default values.
For example,
// Invalid
void add(int a, int b = 3, int c, int d);
// Invalid
void add(int a, int b = 3, int c, int d = 4);
// Valid
Void add(int a, int c, int b = 3, int d = 4); 24
Recursive function
A recursive function is a function that calls itself,
either directly, or indirectly (through another
function).
Some problems are most easily solved by
recursion such as factorials of a number;
Binomial n!/(n!*(n-k)!), Fibonacci series
25
#include<iostream> Example solving factorial
using namespace std; using recursion function
int fact(int n) {
if(n==0)
return 1;
else
return n*fact(n-1);
}
int main() {
int r,n;
cout<<"\n Enter a number:";
cin>>n;
r = fact(n);
cout<<"\n"<<n<<"!="<<r<<endl;
system("Pause");
return 0;
}
26
Built-in function
are functions available in C and C++ standard
library.
Built-in function contains basically return type,
function name, argument lists if necessary
Detail implementation or definition of built-in
function is not visible for the user.
The user only knows
• what the function do,
• what argument it requires and
• what value will be returned
27
Some of cmath functions
Here are some examples of cmath function that use to
perform any mathematical problem specific to that function .
To use cmath function # include <cmath> header is added at
the top of the source file.
Is a built-in function
returns a double value
double hypot(double, double); Hypotenuse of a right
angle triangle
Return type
Function name Argument lists
28
No Some of Built-in cmath function
1 double cos(double);
Takes an angle (as a double) and returns the cosine.
2 double sin(double);
Takes an angle (as a double) and returns the sine.
3 double tan(double);
Takes an angle (as a double) and returns the tangent.
4 double log(double);
takes a number and returns the natural logarithm of that number.
5 double pow(double, double);
The first number is base and the second the power(exponent).
29
6 double hypot(double, double);
By accepting length of two sides of a right triangle, it will return the
length of the hypotenuse.
7 double sqrt(double);
use to calculate square root of a number.
8 int abs(int);
claculate absolute value of an integer.
9 double fabs(double);
Returns the absolute value of any decimal number passed to it.
1 double floor(double);
0 Finds the integer which is less than or equal to the argument passed
to it.
30
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
short s = 10; int i = -1000;
long l = 100000; float f = 230.47;
double d = 200.374;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "floor(d) :" << floor(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "pow( d, 2) :" << pow(d, 2) << endl;
return 0;
} 31