write a program in c++ to swap the value of teo integer variable using call by reference method
Answers
Answered by
2
Answer:
include<iostream>
void swap(int *,int *);
int main ( )
{
int a,b;
a=10;
b=20;
cout<<"a="<<a<<" b="<<b;
swap (&a,&b);
cout<<"\na="<<a<<" b="<<b;
getch ();
return 0;
}
void swap(int *a,int *b)
{
*a = *a - *b; //storing difference
*b = *b + *a; //adding difference
*a = *b - *a; //subtracting difference
}
Adding to Amber Anand's answer
Swapping without third variable.
let a = 5 & b= 2 from
*a = *a - *b; //storing difference
*b = *b + *a; //adding difference
*a = *b - *a; //subtracting
a = 5 – 2; // now a=3
b = 2 + 3; //b=5
a = 5 – 3; // a=2
You can try this for other numbers to get firm understanding of the concept.
hope this helps…
Footnotes
Explanation:
hope you like my answer
Similar questions