Professional Documents
Culture Documents
Programming in C++
Unit 1
Part - 3
Functions
Syntax :
return_type function_name(arguments)
{
body of the function
}
For e.g :
int add(int a,int b)
{
return a+b;
}
Calling a Function
main()/function_1()
A function can be called in {
a main() function or in body
other functions. function(passing values);
}
When it is called inside For e.g :
itself than it called as main()
recursive function. {
int a,b;
cout<<“Sum=“<<add(a,b);
}
int add(int x,int y)
{
return x+y;
}
Call by Value & Call by Reference
• Call by value
– Copy of data passed to function
– Changes to copy do not change original
– Used to prevent unwanted side effects
• Call by reference
– Function can directly access data
– Changes affect original
• Reference parameter alias for argument
– & is used to signify a reference
void change( int &variable )
{ variable += 3; }
– Adds 3 to the variable inputted
int y = &x.
– A change to y will now affect x as well
Call by Value
Output
Call by Reference
Output
Recursion
• Recursive functions
– Are functions that calls themselves
– Can only solve a base case
– If not base case, the function breaks the problem into
a slightly smaller, slightly simpler, problem that
resembles the original problem and
• Launches a new copy of itself to work on the smaller
problem, slowly converging towards the base case
• Makes a call to itself inside the return statement
– Eventually the base case gets solved and then that
value works its way back up to solve the whole
problem
Recursion – Factorial of a number
• Example: factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
– Recursive relationship ( n! = n * ( n – 1 )! )
5! = 5 * 4!
4! = 4 * 3!…
– Base case (1! = 0! = 1)
Recursion – Factorial of a number
Output
Recursion – Fibonacci Series
• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
– Each number sum of two previous ones
– Example of a recursive formula:
fib(n) = fib(n-1) + fib(n-2)
• C++ code for fibonacci function
long fibonacci( long n )
{
if ( n == 0 || n == 1 ) // base case
return n;
else if ( n < 0 )
return –1;
else
return fibonacci( n - 1 ) + fibonacci( n – 2 );
}
Recursion – Fibonacci Series
f( 3 )
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
return 1 return 0
Recursion – Fibonacci Series
Output
Default Arguments
Working of Default Arguments
Default Arguments
Default Arguments
Default Arguments
Returning by reference
Returning by reference
Returning by reference
Function Overloading
Function Overloading
Function Overloading
Passing Parameters by reference
Pass by reference
To pass a variable by reference, we simply declare the function
parameters as references rather than as normal variables:
Example
Function’s parameter is now a
reference instead of a normal
variable.