Swap with pointers. Is it right way to use pointers in order to swap two numbers or is there any simpler method? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Swap with pointers. Is it right way to use pointers in order to swap two numbers or is there any simpler method?

#include <iostream> using namespace std; void swap(int *c, int *d) { int *e, m; e = &m; m = *c; *c = *d; *d = *e; } int main() { int a, b; cout << "Program to swap two numbers using pointers\n" << endl; cout << "Please, input 1st number: "; cin >> a; cout << "Please, input 2nd number: "; cin >> b; swap(a, b); if (a != b) { cout << "\nThe 1st swapped number: " << a << endl; cout << "The 2nd swapped number: " << b << endl; } else cout << "Numbers are equal to each other! Please, input different numbers!" << endl; system("pause"); return 0; }

13th Jan 2019, 7:49 PM
Sabohat Juraeva
Sabohat Juraeva - avatar
2 Answers
+ 1
#include <iostream> using namespace std; void swap(int* x, int* y) { int z = *x; *x = *y; *y = z; } int main() { int a, b; cout<<"a= "; cin>>a; cout<<"\nb= "; cin>>b; swap(&a, &b); cout << "\nAfter Swap\n"; cout << "a = " << a << " b = " << b << "\n"; return 0; } There is best way
13th Jan 2019, 9:39 PM
Jasur Makhsudov
0
Pointers aren't absolutely necessary for this. You don't even need references, but it would save memory to use references. void swap(int& a, int &b) { int tmp = a; a = b; b = tmp; }
14th Jan 2019, 3:05 AM
Zeke Williams
Zeke Williams - avatar