+ 1

Swap numbers without 3rd variable.

Swap two numbers without using 3rd variable.

1st Mar 2017, 6:11 AM
Arbaz Alam
Arbaz Alam - avatar
8 ответов
+ 4
Álvaro don't complain go for temp=a; a=b; b=temp; even objects and structure variables can be swapped with this otherwise need to overload operators
1st Mar 2017, 6:47 AM
Megatron
Megatron - avatar
+ 3
a=a+b-(b=a);
1st Mar 2017, 6:34 AM
Megatron
Megatron - avatar
+ 3
@Raj Kumar Chauhan swap(a,b) in c++ works.
1st Mar 2017, 7:14 AM
Megatron
Megatron - avatar
+ 3
@Raj Kumar Chauhan He wants badge self learner
1st Mar 2017, 7:15 AM
Megatron
Megatron - avatar
+ 2
Not advisable, though, if the int numbers are too large, as this could lead to an overflow problem.
1st Mar 2017, 6:45 AM
Álvaro
0
#include <iostream> using namespace std; int main() { int a,b; a=3; b=5; cin >> a; cin >> b; //swapping without third variable. a=a+b; b=a-b; a=a-b; cout << a; cout << " and "; cout << b; }
1st Mar 2017, 6:12 AM
Arbaz Alam
Arbaz Alam - avatar
0
in python: a, b = b, a you can't get any better way to swap :)
1st Mar 2017, 7:12 AM
Raj Kumar Chauhan
Raj Kumar Chauhan - avatar
0
@arbaz....initializing variables and asking for input also..you seem confused as you ask question and write answer yourself. first decide what do you want
1st Mar 2017, 7:14 AM
Raj Kumar Chauhan
Raj Kumar Chauhan - avatar