Write a C++ program to swap two number by both call by value and call by reference mechanism, using two functions swap_value() and swap_reference respectively , by getting the choice from the user and executing the user’s choice by switch-case.
Implementation of the above problem:
#include<iostream.h>
#include<conio.h>
void main(void)
{
clrscr();
int x,y,n;
void swap1(int,int);
void swap2(int*x,int*y);
cout<<"enter two values to be swapped\n";
cin>>x>>y;
cout<<"\nfor CALL BY VALUE press1";
cout<<"\nfor CALL BY REFERENCE press2";
cin>>n;
switch(n)
{
case 1:
cout<<"\nCALL BY VALUE";
cout<<"\nvalues before swap()"<<x<<"\t"<<y;
swap1(x,y);
cout<<"\nafter swap outside of swap1()";
cout<<"\nx="<<x<<"\ny="<<y;
break;
case 2:
cout<<"\nCALL BY REFERENCE";
cout<<"\nvalue before swap"<<x<<y;
swap2(&x,&y);
cout<<"\nafter swap(outside of swap2)"<<x<<y;
break;
}
getch();
}
void swap1(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
cout<<"\nswapped values(inside swap1())"<<x<<"\t"<<y;
}
void swap2(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
cout<<"\nswapped value(inside swap2())"<<*x<<"\t"<<*y;
}
Thanks
Mukesh Rajput
// swap version using add
ReplyDeletevoid
swap ( int* x, int* y)
{
*x = *x + *y;
*y = *x - *y;
*x = *x - *y;
}
// swap version using or-ex
void
swap2 ( int* x, int* y )
{
*x = *x ^ *y;
*y = *x ^ *y;
*x = *x ^ *y;
}