Você está na página 1de 33

Functions

Subtopics

Functions
Function Declaration
Function Arguments
Return Statements and values
Function
Functions are building blocks of the programs.
They make the programs more modular and easy to read and
manage.
Functions can be called several times in the same program,
allowing the code to be reused.
All C++ programs must contain the function main( ) that too
only one.
The execution of the program starts from the function main( ).
Advantages of Using Functions
Easier to understand , debug and test.
It facilitates top-down modular programming.
The length of source program can be reduced
by using function at appropriate place.
It is easy to locate and isolate a faulty function
for further investigation.
A function may be used by other programs.
Functions
C functions can be classified into two categories
Library Functions((e.g., abs, ceil, rand, sqrt, etc.)
are usually grouped into specialized libraries
(e.g., iostream, stdlib, math, etc.)
User Defined Functions

Difference:
Library functions are inbuilt, where as user defined
function has to be developed by the user at the
time of writing a program.
Elements for the user defined
Functions
Function definition
Function Call
Function declaration
Form of a function
Syntax: Function Declaration
return_type function_name(parameter list) ;
Syntax : Function Call
int main()
{
Function_name(parameter list);
}
Syntax: Function Definition
Function_type function_name(parameter list)
{
local variable declaration;
executable statement1;
executable statement 2;
return;
}
Example

#include<iostream>
int sum1(int a, int b)
{ int c;
c=a+b;
return c;}
int main()
{int y=sum1(2,3);
cout<<y;}
The General Form of a Function is
returntype function-name(parameter-list)
{
Body of the function
}
The function can return any type of data like int, char, float, double
etc.
The parameter list is comma separated list of variable names and
their associated types the receive values of the arguments when the
function is called.
A function may be without parameters or with parameters.

fun(type varname1,type varname2,type varname2.,type var


name N)
Example:
int fun1(int i,int j,int k) is the function whose name is fun1, and it
takes three integer i,j,k and returns int .
Function prototyping

The prototype describes the function interface to the


compiler by giving details such as the number and type of
arguments and the type of return values.

Any violation in matching the arguments or the return types


will be caught by the compiler at the time of compilation itself.

C++ makes the prototyping essential


Function prototyping
#include<iostream>
using namespace std;
int fun1(int, int, int); //function prototype
main()
{
int i=10,j=20,k=30,
int s1;
s1 = fun1(i,j,k);
cout<<"sum is "<<s1;
}
int fun1(int i, int j, int k)
{
int sum;
sum = i+j+k;
return sum;
}
Function prototyping
In function declaration , the names of the arguments are dummy
variables and then they are optional

Ex:
int fun1(int, int, int);
acceptable to the place of declaration, here compiler only checks
the type of arguments when the function is called.

We can also declare a function with an empty argument list


void display();
i.e. the function does not pass any parameters
Similar to void display(void)
Variables that are defined within a function are called local
variables.

int fun1(int i,int j, int k)


{
int sum;
sum = i+j+k;
return sum;
}
Here sum is the local variable.
FUNCTION ARGUMENTS

Formal arguments are the parameters present in a function


definition which may also be called as dummy arguments or
parametric variables. When the function is invoked, the formal
parameters are replaced by the actual parameters.

They behave like other local variables inside the function and
are created upon entry into the function and destroyed upon
exit.
Actual arguments: An actual argument is a variable or an
expression contained in a function call that replaces the formal
parameter which is a part of the function declaration.
FUNCTION ARGUMENTS
#include<iostream>
using namespace std;
int fun1(int, int, int); //prototype declaration
main()
{
int i=10,j=20,k=30,
int s1;
s1 = fun1(i,j,k); // i, j, k are the actual arguments
cout<<"sum is "<<s1;
}
int fun1(int i,int j, int k) //formal parameters or arguments
{
int sum;
sum = i+j+k;
return sum;
}
#include<iostream>
using namespace std;
int fun1(int, int, int); /*function declaration OR function
prototype */
main()
{
int i=10,j=20,k=30; //local variable
int s1;
s1 = fun1(i, j, k); // function calling
cout<<"sum is "<<s1;
}
int fun1(int i, int j, int k) //function definition
{
int sum;
sum = i+j+k;
return sum;
#include<iostream.h>
Example
#include<conio.h>
int factorial(int n);
int main ()
{
int n1,fact;
cout <<"Enter the number whose factorial has to be calculated" << endl;
cin >> n1;
fact=factorial(n1);
cout << "The factorial of " << n1 << " is : " << fact << endl;
getch();
return(0);
}
int factorial(int n)
{ int i=0,fact=1;
for(i=1;i<=n;i++)
{ fact=fact*i; }
return(fact);
}}
Function Call
Parameters Pass/Call by Value
Parameters Pass/Call by Reference
Pass/Call by value

Copies of the arguments are created .


The parameters are mapped to the copies of the arguments
created.
The changes made to the parameter do not affect the
arguments.
Example
#include<iostream.h>
int add(int n);
int main()
{
int number,result;
number=5;
cout << " The initial value of number : " << number
<< endl;
result=add(number);
Example
cout << " The final value of number : " << number
<< endl;
cout << " The result is : " << result << endl;
return(0);
}
int add(int number)
{
number=number+100;
return(number);
}
Default Arguments
A default argument is a value given in the
function declaration that the compiler
automatically inserts if the caller does not
provide a value for that argument in the
function call.
Syntax:

return_type f(, type x = default_value,);


CS 103 22
Default Arguments
(Examples)

double pow(double x, int n=2)


// computes and returns xn
The default value of the 2nd argument is 2.
This means that if the programmer calls
pow(x), the compiler will replace that call
with pow(x,2), returning x2

CS 103 23
Default Arguments
(Rules)
Once an argument has a default value, all
the arguments after it must have default
values.
Once an argument is defaulted in a function
call, all the remaining arguments must be
defaulted.

int f(int x, int y=0, int n) int f(int x, int y=0, int n=1)
// illegal // legal

CS 103 24
Examples of Legal/Illegal Defaulting in Function
Calls
Let substring be a function whose prototype is:

char * substring (char *p, int length=10, int pos=0)


Assume
char
Which call to *p=hello;
substring is OK and which is not OK? If
OK, what is it equivalent to?
substring(p)
substring(p,10)
substring( )

CS 103 25
DEFAULT ARGUMENTS
#include<iostream>
using namespace std;
void sum(int x=10,int y=20); //function prototype declaration
//with default argument list
int main()
{
int a,b;
sum(); //function calling
---------------
---------
}
void sum(int a1,int a2)//function definition
{
int temp;
temp=a1+a2; //a1=10, a2=20 by default arguments
}
//program to use default arguments
#include<iostream.h>
void sum(int a,int b,int c=3,int d=10);
int main()
{
int a,b,c,d;
cout<<enter any two numbers\n;
cin>>a>>b;
sum(a,b);//sum of values sum(a,b,3,10)
return 0;
}
void sum(int a1,int a2,int a3,int a4)
{
int temp;
temp=a1+a2+a3+a4;
cout<<a=<<a1<<endl;
cout<<b=<<a2<<endl;
cout<<c=<<a3<<endl;
cout<<d=<<a4<<endl;
Recursion
When a function call itself directly or indirectly, this is called
recursive call
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{ recursion();
}
The C++ programming language supports recursion, i.e., a function to call
itself. But while using recursion, programmers need to be careful to define
an exit condition from the function, otherwise it will go in infinite loop.
Recursive function are very useful to solve many mathematical problems
like to calculate factorial of a number, generating Fibonacci series, etc.
Coding the factorial function
Iterative implementation
int Factorial(int n)
{
int fact = 1;
for(int count = 2; count <= n; count++)
fact = fact * count;
return fact;
}
Recursive implementation

int Factorial(int n)
{
if (n==0) // base case
return 1;
else
return n * Factorial(n-1);
}
Example of Recursion

factorial(int n) 3
{ fact =3*factorial(3-1)
int fact; fact=3*2*factorial(2-
1)
if(n==1)
fact=3*2*1;
return 1; 2
else 6
For 5
fact=n*factorial(n 2
-1); 6
24
return(fact);
120
}
Example of Recursion
Fibonacci Series
using namespace std;
#include <iostream>
int fibonaci(int i)
{
if(i == 0) { return 0; }
if(i == 1)
{ return 1; }
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{ cout<<"\n"<<(fibonaci(i)); }
return 0;
}
o/p
0 1 1 2 3 5 8 13 21 34
Example of Recursion
Except the fact that the calling and called functions have the
same name, there is really no difference between recursive
and nonrecursive calls
int f(int x)
{
int y;
if(x==0)
return 1;
else {
y = 2 * f(x-1);
return y+1;
}
}
2*f(2)

2*f(1)

2*f(1)

=f(0)

=f(1
)
=f(2)

=f(3)

Você também pode gostar