Functions - Tutorial Focus

Functions
1
Ritika sharma
What is function????
 Function is a self contained block of statements that perform
a coherent task of some kind.
 Every C++ program can be a thought of the collection of
functions.
 main( ) is also a function.
2
Ritika sharma
Types of Functions.
 Library functions
 These are the in- -built functions of ‘C++ ’library.
 These are already defined in header files.
 e.g. Cout<<; is a function which is used to print at output. It is
defined in ‘iostream.h ’ file .
 User defined functions.
 Programmer can create their own function in C++ to
perform specific task
3
Ritika sharma
Actual arguments:-the arguments of calling function are
actual arguments.
b) Formal arguments:-arguments of called function are formal
arguments.
c) Argument list:-means variable name enclosed within the
paranthesis. they must be separated by comma
d) Return value:-it is the outcome of the function. the result
obtained by the function is sent back to the calling function
through the return statement.
a)
4
Ritika sharma
Why use function?
5
Ritika sharma
Why use function
 Writing functions avoids rewriting of the same code again
and again in the program.
 Using function large programs can be reduced to smaller
ones. It is easy to debug and find out the errors in it.
 Using a function it becomes easier to write program to keep
track of what they are doing.
6
Ritika sharma
Function Declaration
ret_type func_name(data_type par1,data_type par2);
Function Defination
ret_type func_name(data_type par1,data_type
par2)
{
}
Function Call
func_name(data_type par1,data_type par2);
7
Ritika sharma
Function prototype
 A prototype statement helps the compiler to check the
return type and arguments type of the function.
 A prototype function consist of the functions return type,
name and argument list.
 Example
 int sum( int x, int y);
8
Ritika sharma
Example
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
void sum(int, int); // function declaration
int a, b, c;
cout<<“enter the two no”;
cin>>a>>b>>c;
sum(a,b); // function calling
getch();
}
void sum( int x, int y)// function definition
{
c=x+y;
cout<< “ sum is”<<c;
}
9
Ritika sharma
#include<conio.h>
void main()
{
clrscr();
int a=10,b=20;
int sum(int, int);
int c=sum(a,b); /*actual arguments
Cout<<“sum is” << c;
getch();
}
int sum(int x, int y)
/*formal arguments
{
int s;
s=x+y;
return(s);
/*return value
}
10
Ritika sharma
Categories of functions
 A function with no parameter and no return value
 A function with parameter and no return value
 A function with parameter and return value
 A function without parameter and return value
11
Ritika sharma
A function with no parameter and no return value
#include<conio.h>
void main()
{
clrscr();
void print();
/*func declaration
Cout<<“no parameter and no return value”;
print();
/*func calling
getch();
}
void print()
/*func defination
{
For(int i=1;i<=30;i++)
{
cout<<“*”;
}
Cout<<“\n”;
}
12
Ritika sharma
A function with no parameter and no
return value
 There is no data transfer between calling and called function
 The function is only executed and nothing is obtained
 Such functions may be used to print some messages, draw
stars etc
13
Ritika sharma
A function with parameter and no return
value.
#include<conio.h>
void main()
{
clrscr();
int a=10,b=20;
void mul(int,int);
mul(a,b);
getch();
}
void mul(int x, int y)
{
int s;
s=x*y;
Cout<<“mul is” << s;
}
14
Ritika sharma
/*actual arguments
/*formal arguments
A function with parameter and return value
#include<conio.h>
void main()
{
clrscr();
int a=10,b=20,c;
int max(int,int);
c=max(a,b);
Cout<<“greatest no is” <<c;
getch();
}
int max(int x, int y)
{
if(x>y)
return(x);
else
{
return(y);
}
}
15
Ritika sharma
A function without parameter and
return value
#include<conio.h>
void main()
{
clrscr();
int a=10,b=20;
int sum();
int c=sum();
/*actual arguments
Cout<<“sum is”<< c;
getch();
}
int sum()
/*formal arguments
{
int x=10,y=30;
return(x+y);
/*return value
}
16
Ritika sharma
Some important points
 A function declaration,defination,and call must match in
number,type and order of actual and formal arguments.
 A function can b called from other function but a function
cannot be defined inside another function
 Function defined and function call order can b different
 The actual arguments in a function can be
variables,constants,or expression where as formal arguments
must be variables
17
Ritika sharma
ARGUMENT PASSING
TECHNIQUES
18
Ritika sharma
Argument passing techniques
 Pass By Value
 Pass By Reference
 Pass By Pointer\address
19
Ritika sharma
Call By Value
 It is a default mechanism for argument passing.
 When an argument is passed by value then the copy of
argument is made know as formal arguments which is stored
at separate memory location
 Any changes made in the formal argument are not reflected
back to actual argument, rather they remain local to the
block which are lost once the control is returned back to
calling program
20
Ritika sharma
Example
void main()
{
int a=10,b=20;
int swap(int,int);
Cout<<“before function calling”<<a<<b;
swap(a,b);
Cout<<“after function calling”<<a<<b;
getch();
Return 0;
}
21
Ritika sharma
void swap(int x,int y)
{
int z;
z=x;
x=y;
y=z;
Cout<<“value is”<<x<<y;
}
22
Ritika sharma
Output:
before function calling a=10 b=20
value of x=20 and y= 10
after function calling a=10 b=20
23
Ritika sharma
Call By pointer/address
 In this instead of passing value, address are passed.
 Here formal arguments are pointers to the actual arguments
 Hence change made in the argument are permanent.
 The address of arguments is passed by preceding the address
operator(&) with the name of the variable whose value you
want to modify.
 The formal arguments are processed by asterisk (*) which acts
as a pointer variable to store the addresses of the actual
arguments
24
Ritika sharma
Example
Void main()
{
int a=10 ,b=25;
void swap(int *,int *);
Cout<<“before function calling”<<a<<b;
swap(&a,&b);
Cout<<“after function calling”<<a<<b;
getch();
}
25
Ritika sharma
void swap(int *x,int *y)
{
int z;
z=*x;
*x=*y;
*y=z;
Cout<<“value is”<<*x<<*y;
}
26
Ritika sharma
Output:
before function calling a= 10 b= 25
value of x=25 and y=10
after function calling a=25 b= 10
27
Ritika sharma
Using Reference Variables
with Functions
 To create a second name for a variable in a program,
you can generate an alias, or an alternate name.
 In C++ a variable that acts as an alias for another
variable is called a reference variable, or simply a
reference
28
Ritika sharma
Declaring Reference Variables
 You declare a reference variable by placing a type and
an ampersand in front of a variable name, as in double
&cash; and assigning another variable of the same type
to the reference variable
double someMoney;
double &cash = someMoney;
 A reference variable refers to the same memory address
as does a variable, and a pointer holds the memory
address of a variable
29
Ritika sharma
Pass By Reference
void main()
{
int i=10;
int &j=i; // j is a reference variable of I
cout<<“value”<<i<<“\t”<<j;
j=20;
cout<<“modified value”<<i<<“\t”<<j;
getch();
}
30
Ritika sharma
Output:Value 10 10
modified value 20 20
31
Ritika sharma
Declaring Reference Variables
 There are two differences between reference variables
and pointers:
 Pointers are more flexible
 Reference variables are easier to use
 You assign a value to a pointer by inserting an
ampersand in front of the name of the variable whose
address you want to store in the pointer
 It shows that when you want to use the value stored in
the pointer, you must use the asterisk to dereference the
pointer, or use the value to which it points, instead of
the address it holds
32
Ritika sharma
 Call by value This method 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.
 Call by pointer 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 that changes made to the parameter affect the
argument.
 Call by referenceThis 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.
33
Ritika sharma
INLINE FUNCTIONS
34
Ritika sharma
Inline Functions
 Each time you call a function in a C++ program, the computer
must do the following:
 Remember where to return when the function eventually ends
 Provide memory for the function’s variables
 Provide memory for any value returned by the function
 Pass control to the function
 Pass control back to the calling program
 This extra activity constitutes the overhead, or cost of doing
business, involved in calling a function.
35
Ritika sharma
 Solution to this is to replace each function call with the
necessary code instead of making function.
 Inline function is a function which gets expanded inline at
each point in the program where it is called.
 In other words inline functions are those functions whose
function body is inserted in place of the function call during
the compilation process.
 Syntax:
inline ret_type func_name(parameter_list)
{
function body
}
36
Ritika sharma
inline int max(int x,int y)
{
return (x>y?x:y);
}
int main()
{
int m=10,n=25;
int a,b;
a=max(6,8);
cout<<“greatest is”<<a;
b=max(m,n);
cout<<“greates of m=“<<m<<“ and n=“<<n <<“is “<<b;
getch();
return 0;
}
37
Ritika sharma
 Output :
Greatest of 6 and 8=8
Greatest of m=10 and n=25 is 25
38
Ritika sharma
 An inline function is a small function with no calling overhead
 Overhead is avoided because program control never transfers to
the function
 A copy of the function statements is placed directly into the
compiled calling program
 The inline function appears prior to the main(), which calls it
 Any inline function must precede any function that calls it,
which eliminates the need for prototyping in the calling
function
39
Ritika sharma
 When you compile a program, the code for the inline
function is placed directly within the main() function
 You should use an inline function only in the following
situations:
 When you want to group statements together so that you can use a
function name
 When the number of statements is small (one or two lines in the body of
the function)
 When the function is called on few occasions
40
Ritika sharma
Disadvantages:
 All functions that uses the inline function must be recompiled
if any changes are made to the inline function.
 Although inline function reduces the execution time. It
increases the size of the executable file as multiple copies of
the inline functions body are inserted in the programs. So it
is always recommended to use inline functions for small
frequently used functions.
 The definition of inline function should appear before the
function call.
41
Ritika sharma
Some places where inline not work
 For functions returning values if a loop,a switch or goto
exits.
 For functions returning values if return statement exists.
 If function contains static variables.
 If inline functions are recursive.
42
Ritika sharma
DEFAULT ARGUMENTS
43
Ritika sharma
DEFAULT ARGUMENTS
 Default arguments is useful in situation where a arguments has
the same value in most function calls.
 When the desired value is different from the default value,the
desired value can be specified explicity in a function call.
 This changes the default value of the argument to be overridden
for the duration of function call.
If in the function call all the arguments are not specified then the
omitted arguments can take default value by providing them in
the function declaration.
44
Ritika sharma
void volume(int l=10,int w=10,int h=10); //function declatration
int main()
{
volume ();
volume(5);
volume(8,6);
volume(6,4,5);
getch();
return 0;
}
void volume(int l,intw,int h)
{
Cout<<“volume =“<<l*w*h<<endl;
}
Output:
Volume:1000
Volume:500
Volume:480
Volume:120
45
Ritika sharma
Using Default Arguments
 When you don’t provide enough arguments in a function call,
you usually want the compiler to issue a warning message for this
error
 Sometimes it is useful to create a function that supplies a default
value for any missing parameters
46
 Two rules apply to default parameters:
 If you assign a default value to any variable in a
Ritika sharma
function prototype’s parameter list, then all
parameters to the right of that variable also must
have default values.
 If you omit any argument when you call a function
that has default parameters, then you also must
leave out all arguments to the right of that argument
47
Ritika sharma
Examples of Legal and Illegal
Use of Functions with Default Parameters
48
Ritika sharma
Restrictions on Default parameter
 All parameters to the right of a perameter with default






49
argument must have default arguments.
For eg: voidf(int,double=0.0,char*)
//error(missing default parameter for 3rd parameter)
Default parameter cannot be redefined.
Void(int, double=0;char*=Null)
Void(int,double=1;char*=Null)
If you are using defaut parameter,values will be assigned from
left to right.
Ritika sharma
RECURSIVE FUNCTIONS
50
Ritika sharma
Recursion
 When function call itself repeatedly ,until some specified
condition is met then this process is called recursion.
 It is useful for writing repetitive problems where each
action is stated in terms of previous result.
 The need of recursion arises if logic of the problem is such
that the solution of the problem depends upon the
repetition of certain set of statements with different input
values an with a condition.
51
Ritika sharma
Two basic requirements for recursion :
1. The function must call itself again and again.
2. It must have an exit condition.
52
Ritika sharma
53
int main()
{
int factorial (int);
int x,fact;
cout<<“enter a number=“;
cin>>x;
fact=factorial(x);
cout<<“\n factorial of”<<x<<“=“<<fact;
getch();
return 0;
}
int factorial(int a)
{
int b;
if(a==1)
return (1);
else
b=a*factorial(a-1);
return (b);
}
Ritika sharma
 Output:
Enter a number=3
Factorial0f 3=6
54
Ritika sharma
Stack representation
.
3*2*fact(1)
.
3*fact(2)
fact(3)
fact(3)
3*2*1
3*2*fact(1)
3*fact(2)
fact(3)
55
Ritika sharma
3*fact(2)
fact(3)
Fibonacci using recursion
int main()
{
int fib(int);
int n;
cout<<“enter the number of terms=“;
cin>>n;
for(int i=1;i<=n;i++)
cout<<fib(i)<<“ “;
getch();
return o;
}
int fib(int m)
{
if(m==1|| m==2)
return(1);
else
return(fib(m-1)+fib(m-2));
}
56
Ritika sharma
Advantages of recursion
1. It make program code compact which is easier to write and
understand.
2. It is used with the data structures such as linklist,stack,queues
etc.
3. It is useful if a solution to a problem is in repetitive form.
4. The compact code in a recursion simplifies the compilation as
less number of lines need to be compiled.
57
Ritika sharma
Disadvantages
1. Consume more storage space as recursion calls and
automatic variables are stored in a stack.
2. It is less efficient in comparison to normal program in case
of speed and execution time
3. Special care need to be taken for stopping condition in a
recursion function
4. If the recursion calls are not checked ,the computer may
run out of memory.
58
Ritika sharma
FUNCTION
OVERLOADING
59
Ritika sharma
Polymorphism
 The word polymorphism is derived from Greek word Poly
which means many and morphos which means forms.
 Polymorphism can be defined as the ability to use the same
name for two or more related but technically different tasks.
 Eg-woman plays role of daughter,sister,wife,mother etc.
60
Ritika sharma
Overloading in C++
 What is overloading
– Overloading means assigning multiple
meanings to a function name or operator
symbol
– It allows multiple definitions of a function with the same
name, but different signatures.
 C++ supports
– Function overloading
– Operator overloading
61
Ritika sharma
Why is Overloading Useful?
 Function overloading allows functions that
conceptually perform the same task on
objects of different types to be given the
same name.
 Operator overloading provides a convenient
notation for manipulating user-defined
objects with conventional operators.
62
Ritika sharma
Function Overloading
 Is the process of using the same name for two or more
functions
 Requires each redefinition of a function to use a different
function signature that is:
 different types of parameters,
 or sequence of parameters,
 or number of parameters
 Is used so that a programmer does not have to remember
multiple function names
63
Ritika sharma
Function Overloading
 Two or more functions can have the same name but different
parameters
 Example:
int max(int a, int b)
{
if (a>= b)
return a;
else
return b;
}
64
Ritika sharma
float max(float a, float b)
{
if (a>= b)
return a;
else
return b;
}
Overloading Function Call Resolution
 Overloaded function call resolution is done by
compiler during compilation
– The function signature determines which definition
is used
 a Function signature consists of:
– Parameter types and number of parameters
supplied to a function
 a Function return type is not part of function signature
and is not used in function call resolution
65
Ritika sharma
void sum(int,int);
void sum(double,double);
void sum(char,char);
void main()
{
int a=10,b=20 ;
double c=7.52,d=8.14;
char e=‘a’ , f=‘b’ ;
sum(a,b);
//calls sum(int x,int y)
sum(c,d);
//calls sum (double x,double y)
sum(e,f);
// calls sum(char x,char y)
}
void sum(int x,int y)
{
vout<<“\n sum of integers are”<<x+y;
}
void sum(double x,double y)
{
cout<<“\n sum of two floating no are”<<x+y;
}
void sum(char x,char y)
Ritika sharma
66 {
cout<<“\n sum of characters are”<<x+y;
 Output:
Sum of integers 30
sum of two floating no are 15.66
sum of characters are 195
67
Ritika sharma
Void area(int)
Void area(int,int);
Void area(int,int,int);
Int main()
{
Int side=10,le=5,br=6,a=4,b=5,c=6;
Area(side);
Area(le,br);
Area(a,b,c);
Getch();
Return 0;
}
Void area(int x)
{ cout<<“area is”<<x*x;
}
Void area(int x,int y)
{cout<<“area of rectang;e”=<<x*y;
}
Void area(int x,int y,int z)
{cout<<“volume is”<<x*y*z;
68
}
Ritika sharma
Function Selection Involves following
Steps.
 Compiler first tries to find the Exact match in which the type
of argument are the same,and uses that func.
 If an exact match is not found,the compiler user the integral
promotions to the actual argument such as,char to int, float
to double.
 When either of them fails ,build in conversions are
used(implicit conversion) to the actual arguments and then
uses the function whose match is unique.but if there are
multiple matches,then compiler will generate an error
message.
69
Ritika sharma
 For ex:
long square(long n)
long square(double x)
Now a func. call such as square(10) will cause an
error because int argument can be converted into
long also and double also.so it will show ambiguity.
User defined conversion are followed if all the
conversion are failed.
70
Ritika sharma
SCOPE RULES
71
Ritika sharma
Scope
 The scope of a variable is the portion of a program where the
variable has meaning (where it exists).
 A global variable has global (unlimited) scope.
 A local variable’s scope is restricted to the function that
declares the variable.
 A block variable’s scope is restricted to the block in which
the variable is declared.
72
Ritika sharma
Understanding Scope
 Some variables can be accessed throughout an entire
program, while others can be accessed only in a limited part
of the program
 The scope of a variable defines where it can be accessed in a
program
 To adequately understand scope, you must be able to
distinguish between local and global variables
73
Ritika sharma
Local variables
 Parameters and variables declared inside the definition of a
function are local.
 They only exist inside the function body.
 Once the function returns, the variables no longer exist!
 That’s fine! We don’t need them anymore!
74
Ritika sharma
Block Variables
 You can also declare variables that exist only within the body
of a compound statement (a block):
{
int foo;
…
…
}
75
Ritika sharma
Global variables
 You can declare variables outside of any function definition –
these variables are global variables.
 Any function can access/change global variables.
 Example: flag that indicates whether debugging information
should be printed.
76
Ritika sharma
Distinguishing Between Local
and Global Variables
 Celebrity names are global because they are known to people
everywhere and always refer to those same celebrities
 Global variables are those that are known to all functions in a
program
 Some named objects in your life are local
 You might have a local co-worker whose name takes
precedence over, or overrides, a global one
77
Ritika sharma
A note about
Global vs. File scope
 A variable declared outside of a function is available
everywhere, but only the functions that follow it in the file
know about it.
 The book talks about file scope, I’m calling it global scope.
78
Ritika sharma
Block Scope
int main(void) {
int y;
{
int a = y;
cout << a << endl;
}
cout << a << endl;
}
79
Ritika sharma
MANIPULATOR FUNCTIONS
80
Ritika sharma
 These are special stream functions that change certain
characteristics of input and output.
 The main advantage of using manipulator functions is that
they facilitate the formatting of input and output stream.
 To carry out the operations of these manipulator functions
the header file <iomanip.h> must be included.
81
Ritika sharma
Following are the standard manipulators normally used
in the stream classes:
 endl
 hex,dec,oct
 setbase
 setw
 setfill
 setprecision
82
Ritika sharma
endl
 It is an output manipulator to generate a next line character.
 cout<<“a”<<endl<<“b”
83
Ritika sharma
Setbase()
 Used to convert the base of one numeric value into another
base
#include<iomanip.h>
Void main()
{
int value;
Cout<<“enter number”<<endl;
Cin>>value;
Cout<<“decimal base “<<setbase(10)<<value;
cout<<“hexadecimal base”<<setbase(16)<<value;
Cout<<“octal base”<<setbase(8)<<value;
}
84
Ritika sharma
 Output:
Enter number 10
Decimal base 10
Hexadecimal base=a
Octal base 12
85
Ritika sharma
Setw()
 It is used to specify the minimum number of character
position on the output field a variable will consume.
void main()
{
int a=200,b=300;
cout<<setw(5)<<a<<setw(5)<<b<<endl;
cout<<setw(6)<<a<<setw(6)<<b<<endl;
cout<<setw(7)<<a<<setw(7)<<b<<endl;
cout<<setw(8)<<a<<setw(8)<<b<<endl;
}
86
Ritika sharma
 Output:
200 300
200 300
200
300
200
300
87
Ritika sharma
Setfill()
 It is used to specify a different character to fill the unused field
width of the value.
void main()
int a=200,b=300;
cout<<“setfill(‘*’);
cout<<setw(5)<<a<<setw(5)<<b<<endl;
cout<<setw(6)<<a<<setw(6)<<b<<endl;
}
Output:
**200***300
***200***300
88
Ritika sharma
Setprecision()
 It is used to control the number of digits of an output
stream display of a floating point value.
 The default precision is 6
void main()
{
float a=5,b=3,c=a/b;
cout<<setprecision(1)<<c<<endl;
cout<<setprecision(2)<<c<<endl;
cout<<setprecision(3)<<c<<endl;
}
Output:
1.7
1.67
1.667
89
Ritika sharma