C++ || Snippet – How To Swap Two Numbers Without Using A Third “Temporary” Variable
The following are three programs which demonstrates how to swap two numbers without using a third “temporary” variable.
Why would anyone want to swap two numbers without utilizing a third variable? There is no real reason to do so other than the fact that exercises such as these are typically used as programming assignments/interview questions. This is a technique that’s rarely ever practical in a real world setting, but it is still an interesting task nonetheless.
12345678910111213141516171819202122232425262728
#include <iostream>using namespace std; int main() { // declare variables int x = 0; int y = 0; // get data cout <<"Please enter two numbers: "; cin >> x >> y; cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; cout <<"nSwitching the numbers..n"; // switch the numbers using simple math x = x+y; y = x-y; x = x-y; cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; return 0;}// http://programmingnotes.org/
SAMPLE OUTPUT:
Please enter two numbers: 7 28
Item #1 = 7
Item #2 = 28Switching the numbers..
Item #1 = 28
Item #2 = 7
12345678910111213141516171819202122232425262728
#include <iostream>using namespace std; int main() { // declare variables int x = 0; int y = 0; // get data cout <<"Please enter two numbers: "; cin >> x >> y; cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; cout <<"nSwitching the numbers..n"; // switch the numbers using the xor swap algorithm x ^= y; y ^= x; x ^= y; cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; return 0;}// http://programmingnotes.org/
SAMPLE OUTPUT:
Please enter two numbers: 5 12453
Item #1 = 5
Item #2 = 12453Switching the numbers..
Item #1 = 12453
Item #2 = 5
123456789101112131415161718192021222324252627
#include <iostream>#include <algorithm>using namespace std; int main() { // declare variables int x = 0; int y = 0; // get data cout <<"Please enter two numbers: "; cin >> x >> y; cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; cout <<"nSwitching the numbers..n"; // switch the numbers using the in-built swap function swap(x, y); cout <<"nItem #1 = "<<x<<endl; cout <<"Item #2 = "<<y<<endl; return 0;}// http://programmingnotes.org/
SAMPLE OUTPUT:
Please enter two numbers: 2132 6547546
Item #1 = 2132
Item #2 = 6547546Switching the numbers..
Item #1 = 6547546
Item #2 = 2132
Leave a Reply