C++ Program To Swap Two Numbers Using Functions

Problem :- Write A C++ Program To Swap Two Numbers Call By Reference/Call By Value Using Functions .

Logic :- There are two method you can use to swap Two Number using function
1. Call by Reference
2. Call by Value

Call by Reference :- In Call by reference we pass address of variable in function not value of variable .

Call by Value :- In Call by Value we pass value of variable in function .

Solution :-

Method 1 :- Call by Reference

#include<iostream>
using namespace std;

void swap(int *x ,int *y );
//Call By Reference
int main()
{
int a,b;
cout<<"\nEnter Two Number You Want To Swap \n";
cin>>a>>b;

swap(&a,&b);

cout<<"\nAfter Swapping Numbers Are Given below\n\n";
cout<<a<<"   "<<b<<" \n";

return 0;
}
void swap(int *x,int *y)
{
int z;
z=*x;
*x=*y;
*y=z;
}

Method 2 :- Call by Value

#include<iostream>
using namespace std;

void swap(int ,int );
//Call By Value
int main()
{
int a,b;
cout<<"\nEnter Two Number You Want To Swap \n";
cin>>a>>b;
cout<<"\nAfter Swapping Numbers Are Given below\n\n";
swap(a,b);
return 0;
}
void swap(int x,int y)
{
int z;
z=x;
x=y;
y=z;
cout<<x<<"   "<<y<<" \n";
}

Output:-

1. Call By Reference

2. Call By Value