swap() by passing pointers

Nov 22, 2016 at 9:05pm
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace 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.
Nov 22, 2016 at 9:54pm
closed account (E0p9LyTq)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

void swap(int *a, int *b)
{
   *a = *a + *b;
   *b = *a - *b;
   *a = *a - *b;
}
int main()
{
   int n1 = 0;
   int n2 = 0;
   std::cout << "Please enter n1: ";
   std::cin >> n1;
   std::cout << "and n2: ";
   std::cin >> n2;

   swap(&n1, &n2);

   std::cout << "\nAfter swapping, n1 = " << n1 << " and n2 = "<< n2 <<"\n";
}

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
Nov 22, 2016 at 10:26pm
closed account (E0p9LyTq)
I personally prefer this solution, it is super geeky:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

void swap(int *a, int *b)
{
   *a ^= *b;
   *b ^= *a;
   *a ^= *b;
}

int main()
{
   int n1 = 0;
   int n2 = 0;
   std::cout << "Please enter n1: ";
   std::cin >> n1;
   std::cout << "and n2: ";
   std::cin >> n2;

   swap(&n1, &n2);

   std::cout << "\nAfter swapping, n1 = " << n1 << " and n2 = "<< n2 <<"\n";
}
Topic archived. No new replies allowed.