Beruflich Dokumente
Kultur Dokumente
Balagurusamy
Advantages of functions:-
Syntax:-
Example:-
2. Function Calling.
- Function is called when a function name is followed by a semi comma.
- Whenever function is called, actual parameters of calling functions are copied
into formal parameters of called function(if any).
- Number of actual and formal parameters should be same(if any).
- Name of actual and formal parameters may be same or different(if any).
- We can call functions using(also called Parameter Passing)
i. Call by Value.
ii. Call by reference.
Syntax:-
function_name(parameter_list);
Example:-
1. add(a,b);
2. add(&a, &b);
Example 1. Shows it is call by value & 2 is call by reference.
3. Function Definition.
- User define functions definition consists of following two parts.
i. Function Header.
It contains ‘return type’, ‘function name’ & ‘argument list’
Function header is not terminated by a semi colon.
ii. Function Body
Function body should be enclosed in curly braces ‘{‘ & ‘}’.
It contains executable statements along with return value, if
any.
These executable statements performs well define task.
Syntax:-
//function body.
Example:-
Actual Parameter
int a,b,c;
cout<<“Enter two numbers\n”;
cin>>a>>b; Function Call.
c=sum(a,b);
Formal Parameter cout<<“Add is ”<<c;
getch(); Function Header
}
Function Definition
int sum(int a, int b){
Function Body
return a+b;
}
Call by Value
int main( ){
int n1,n2;
cout<<“Enter two number:”);
cin>>n1>>n2;
cout<<“In main() b4 function call n1=”<<n1<< “ n2=”<<n2;
swap(n1,n2);
cout<<“In main() after function call n1=”<<n1<< “n2=”<<n2;
return 0;
}
Output
Output
Multiplication is 72
Global Variable:-
int x=50;
Global Variable
main(){
int x=10;
Local Varaible
cout<<“Local Variable x=”<<x<<’\n’;
cout<<“Global Varaible x=”<<::x;
Scope resolution ( :: }
) operator to
distinguish global
Output
variable from local
Local Variable x=10
variable as both have
Global Variable x=50
same name.
main( ){
cout<<“I will stop\n”;
main( );
}
Output
I will stop
I will stop
I will stop
I will stop
1. Direct Recursion
o Calling same function within same function recursively.
o Example:-
main( ){
cout<<“I will stop\n”;
main( );
}
2. Indirect Recursion
o Calling second function from first function and second and second
function have call to first function, it is indirect recursion.
o Example:-
void msg( );
void main(){
cout<<“I am in main( )\n”;
msg( );
}
void msg( ){
cout<<“I am in msg( )\n”;
main( );
}
main( ){
int n,s;
cout<<“Enter value of n:”;
cin>>n;
s=sum(n);
cout<<"Sum of series is "<<s;
}
Output
Sum of series is 66
Enter number:5
Factorial of 5 is 120