Definition:
Functions are the piece of code that performs a specific task. Functions are also called modules or procedures.
Types of Programming based on functions:-
1.Monolithic Programming:-If all the piece of code is written in the main() function then that type of programming is called monolithic programming.
int main(){
int length,breadth,area;
cout<<"Enter the Length and breadth of rectangle:";
cin>>length>>breadth;
area=length*breadth;
cout<<area;
}
2.Modular Programming:-If the entire code is divided into small different functions then that type of programming is called modular programming.
int area(int length,int breadth){
int area=length*breadth;
return area;
}
int perimeter(int length,int breadth){
int perimeter=2*(length+breadth);
return perimeter;
}
int main(){
int length=5,breadth=6;
cout<<area(length,breadth)<<endl;
cout<<perimeter(length,breadth);
}
1. In modern programming practices, modular programming is widely used instead of monolithic programming.
2. In monolithic programming, if an error occurred in the program then we cannot debug the code easily because our entire piece of code is present in the main function.
3. In modular programming we can inspect and debug our code easily due to the division of code into small functions.
Parameters in Functions:-
int add(int a,int b)//Formal Parameters{
int c=a+b;
return c;
}
int main(){
int a=5,b=6,c;
c=add(a,b);//actual Parameters
}
Parameter Passing in Functions:-
1.Call by Value:-
void swap(int x,int y){
int temp;//Local Scope
temp=x;
x=y;
y=temp;
}
int main(){
int a=10,b=20; //main scope
swap(a,b);
cout<<a<<" "<<b;
}
In pass by value, the parameters are available in the local scope and until and unless they are returned, they are not useful. So, therefore it does not affect the main function.
2.Call by Address:-
void swap(int *x,int *y){
int temp;
temp=*x;
*x=*y;
*y=temp;
}
int main(){
int a=10,b=20;
swap(&a,&b);
cout<<a<<" "<<b;
}
The variables of One function cannot access the variable of other functions, but due to pointers, it is possible to access the variables indirectly bypassing the address and storing it via a pointer.
3.Call by Reference:-
Q)What is Reference in C++?
Ans)Reference in C++ means giving an alternate name to a variable.
int a=10 int &r=a;//reference |
The reference variable must be initialized when declared.
If we change any one of the variable values, then it will affect the other one too.
void swap(int &a,int &b){
int temp;
temp=x;
x=y;
y=temp;
}
int main(){
int a=10,b=20;
swap(a,b)
cout<<a<<" "<<b;
}