C++M-I(12,13)
C++M-I(12,13)
Function
I.What is Function? II. Advantage of FunctionIII.Types of FunctionIV. Different parts
of Functions.
V.Category of FunctionsVI. Recursion VII. Default ArgumentVIII. Tutorials
Lecture: 12:
I. What is Function?
Function is a self-content block of statement or subprogram used for
reusability of same block of statements, for avoiding duplication of
programming code.
To re-use the same part of a program, we can define a function, which takes
parameters, and returns a result of various types.
A function is a named unit of a group of program statements that can be
invoked from other part of the program.
In C, any program contains at least one function.
If a program contains only one function, it must be main() function.
If a C program contains more than one function, the one of the function must
be main().
C compiler executes the program from main() function.
II. Advantages of Function
1. It supports modular programming.
2. It avoids rewriting of the same code over and over.(Avoid Code Duplication)
3. It length of a source program can be reduced by using function.
4. It is easy to locate and debug the program errors.
5. It can be called repeatedly.(Code Reusability)
6. Creation of our own library by collecting together a set of functions.
7. Recursive call
III. Types of Function
C function has classified into two categories.
1. Library function
2. User defined function
1. Library Function: The functions, which are pre-defined functions that
can be used in any program by including the respective header file, are
called library functions.Thereis no need to write code for the function.
CSE/C++/Module-I/Trilochan Rout/Lecture: 12, 13 2
2. Example:
Header Library function
File
math.h sqrt(), pow(), abs(), etc.
string.h strlen(), strcpy(),
strcat(), etc.
stdio.h printf(), scanf(), etc.
conio.h getch(), clrscr()
3. User Defined Function: The functions, which are needed to write at the
time of writing program. This function can later become a part of the C++
program library. Example: main()
Main Function:
o In C++, the main function returns a value of type int to the operating
system (OS).
o Therefore C++ explicitly defines main () to match anyone of the following
prototypes:
int main()
int main(int argc, char *argv[]);
o The main function definition in C++ must contain a return statement.
Otherwise it gives an error statement.
Example:
int main()
{
statements;
.....
.....
return 0; It indicates successful
} execution
o Since the return-type of every function by default is int. so the keyword
int in main() function is optional.
o But here the return-type can be declared as void, if void return-type is
declared then there is no need to use the return statement.
NB:
1. The main () function cannot be overloaded.
2. It cannot be declared as inline function.
IV. Different parts of Functions
A function consists the following parts:
1. Function Prototype
2. Function Definition (Called Function)
3. Function Call (Calling Function)
4. Actual & Formal Arguments
5. The return statement5
Function Declaration (Function Prototype)
When a function is declared before its use, this type of declaration is known as
prototype declaration and the name is known as prototype name. The
prototype of the function is generally known as signature of the function.
Prototype has two advantages i.e.,
CSE/C++/Module-I/Trilochan Rout/Lecture: 12, 13 3
1. If identifies the return type of the function, so a compiler can generate the
correct code for the return type.
2. It specifies the type and number of arguments used by function.
Syntax:<return type><function-name>(<parameter list>);
Points to remember about Function:
1. Function prototype ends with’ ; ‘.
2. The parameter list must be separated by commas.
3. The parameter need not be same in between function declaration and
function definition.
4. The types must be match with the type of parameters in the function
definition, in number and order.
5. Use of parameter name in the declaration is optional.
6. If function definition has no formal parameter, in function declaration has a
parameter (void).
7. The return type is optional, when the function returns int data type.
8. The return type must be void if no value is returned.
9. If, the mismatch of data type and the number of argument and return type,
complier will produce an error.
10. It can be declare inside the function before used and above all the
function.
Example:
void show(void);
int sum(int, int);
float mul( int x, int y);
Function Definition
The definition of a function contains the code that implements the function.
The function definition is a set of statements that tells the compiler what to do
when the function is called. In C, a function must be defined before it is
used/called anywhere in the program. This is also known as called function.
Syntax of the Function Definition
<return type><function-name>(<parameter list>)
{
local variable declaration;
statement;
statement;
…..
}
Where:
<return type> is the type of data returned by function. If, return type is
omitted, then it is assumed as int& need to write the return statement.
<function-name> is a name, which makes it possible to call the function at the
time of call. A rule for naming the function-name is same as for variable name.
Local variable: The variables, which are declare within a function, is called
local variable.
Example:
CSE/C++/Module-I/Trilochan Rout/Lecture: 12, 13 4
1. A function is called without taking any formal arguments from the calling portion
of a program and also there is no return statement from the called function.
Example
void sum(); //function prototype
void main()
{
sum(); //calling function
getche();
}
void sum() //function definition
{
int a=10,b=20,c;
c=a+b;
printf(“%d”,c);
return;
}
2. A function is called with passing of some formal arguments to the function from
call portion of a program but the function does not return back any values to the
calling portion.
void sum(int,int); //function prototype
void main()
{
sum(12,20); //calling function
getche();
}
void sum(int a,int b) //function definition
{
int c;
c=a+b;
printf(“%d”,c);
return;
}
3. A function is called with passing of some formal arguments to the function from
calling a portion of a program and returned back some values to the calling
function.
int sum(int,int); //function prototype
void main()
{
printf(“%d”,sum(12,20)); //calling function
getche();
}
int sum(int a,int b) //function definition
{
int c;
c=a+b;
return;
}
4. A function is called without taking any formal arguments from the calling portion
of a program and returns a value from the called function.
int sum(); //function prototype
void main()
{
printf(“%d”,sum()); //calling function
getche();
}
int sum() //function definition
CSE/C++/Module-I/Trilochan Rout/Lecture: 12, 13 7
{
int a=10,b=20,c;c=a+b;return c;}
VI. Recursion
A function is called recursion if a statement in the body of the function calls
itself. Recursion is a process of defining something in terms of itself. C
functions may be used recursively; i.e., a function may call itself either
directly or indirectly.
Direct Call
fun1()
{
………..
fun1();
……
…..
}
In above, the function fun1() called itself directly.
Indirect Call
fun1() fun2()
{ {
……….. ………..
fun2(); fun1();
and
…… ……
….. …..
} }
The function fun1() calls itself indirectly, i.e., function fun1() calls fun2() and
fun2() once again calls function fun1().
To solve a problem recursively, two conditions must be satisfied.
1. The problem must be written in a recursive form.
2. The problem statement must include a stopping condition.
Example: Write a program to find the factorial of a number by using recursive
method of function.
void main()
{
int n=10;
f=fact(n);
printf(“%d”,f);
getche();
}
int fact(int x)
{
if (x==0)
return 1;
else
return x*fact(x-1);
}
During the program execution, as the function calls itself, a stack of pointer is
created in memory. Once the stopping condition is true the control returns to
the address of the instruction stored at the top of the stack (TOS) in order to
complete the execution by addressing the next address stored below and this
goes on till the end and delete stack automatically. Remember, when the
function is invoked, their values are loaded in the different portion of the
CSE/C++/Module-I/Trilochan Rout/Lecture: 12, 13 8
memory. If the value 0 is enter into the function definition, the stack is not
created and the function return 1.
Return values
fact (0) returns 1 fact(1) return 1 (1*0!)
It is not put in stack fact(2) return 2 (2*1!)
because it does not fact(3) return 6 (3*2!)
call the function. fact(4) return 24 (4*3!)
fact(5) return 120 (5*4!)
Drawbacks of Recursive Function
1. Recursion will take more memory space.
2. The execution time will be maximized.
3. It causes a stack overrun.
A function can be invoked either by call by value or by call by reference method.
Call by Value
In Call by Value method, the called function creates its own copies of original
value (actual argument) to it. Any changes that are made occur on the
function’s copy of values and are not reflected back to the calling function.
So, any value change to the formal arguments does not change the value of
the actual argument.
Example
void change(int); //prototype declaration
void main()
{
int x=10;
change(x); //calling function
printf(“The Value of X : %d”,x);
getche( );
}
void change (int a ) //function definition
{
a=a+20;
}
Output:
The Value of X : 10
Call by Reference
In Call by Reference method, the called function accesses and works with the
original values (send by calling function) using their reference.
Any changes that occur on the function definition are reflected back to the
calling function. So, any value change to the formal arguments will change
the value of the actual argument. In this case, we should send the address of
variables to the formal argument and a pointer variable should be used in
formal argument.
Example
void change(int *); //prototype declaration
void main()
{
int x=10;
change(&x); //calling function
printf(“The Value of X : %d”,x);
getche( );
}
void change (int *a )//function definition
Output:
The Value of X: 30
CSE/C++/Module-I/Trilochan Rout/Lecture: 12, 13 9
{
*a=*a+20;
}
Return by reference:
A function can also return a reference to a variable.
int main()
{
int a,b,c;
cout<<”Enter the values for and b:”<<endl;
cin>>a>>b;
int &max(int &, int &);
c=max(a,b);
cout<<”The maximum number is:”<<c;
}
int &max(int &x, int &y)
{
if(x>y)
return x;
else
return y;
}
Output:
Enter the values for a and b: 10 20
The maximum number is 20
int c=4;
int d=5;
cout<<”Sum=”<<sum(a,b,c,d)<<endl;
cout<<”Sum=”<<sum(a,b,c)<<endl;
cout<<”Sum=”<<sum(a,b)<<endl;
cout<<”Sum=”<<sum(a)<<endl;
cout<<”Sum=”<<sum(b,c,d)<<endl;
return 0;
}
int sum(int j, int k, int l, int m )
{
return (j+k+l+m);
}
Output:
Sum=14
Sum=29
Sum=40
Sum=47
Sum=32