Write a swap() function that only takes pointers to two integer variables as parameters and swaps the contents in those variables using the above pointers and without creating any extra variables or pointers The swapped values are displayed from the main(). Demonstrate the function in a C++ program.
Tip: Before using pointers, it will be a good idea to figure out the logic to swap two variables without need of any extra variables. Then, use pointer representations in that logic.
Enter n1 n2: 10 7
After swapping, n1=7 and n2=10
#include <iostream>
usingnamespace std;
void swap(int *a, int *b){
int x = *a;
*a = *b;
*b = x;
}
int main(){
int n1 = 0, n2 = 0;
cout<<"Please enter n1: ";
cin>>n1;
cout<<"and n2: ";
cin>>n2;
swap(&n1, &n2);
cout<<"After swapping, n1="<<n1<<" and n2="<<n2<<"";
return 0;
}
My code works, but it doesn't follow my assignment's instructions because I created the new variable x in the swap function. Is there a way to do this without creating a new variable or pointer? Preferably using more basic code like what i have because i am pretty new to c++ still.
Please enter n1: 5
and n2: 112
After swapping, n1 = 112 and n2 = 5
There is the possibility of overflow wraparound when adding the two variables, can be minimized by using unsigned ints and/or restricting the values the user can input.
See this:
http://stackoverflow.com/questions/3647331/how-to-swap-two-numbers-without-using-temp-variables-or-arithmetic-operations#3647337