0

Write program swap two number

15th Nov 2017, 1:31 PM
Umar Bacha
Umar Bacha - avatar
8 Réponses
+ 18
C/C++/Java/JavaScript/C# temp = a a = b b = temp Python/Ruby a, b = b, a
15th Nov 2017, 1:36 PM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 4
import java.Util.* ..... ..... .... ..... ..... int a,b; a=(a+b)-a; b=(a+b)-b; sopln(a); sopln(b); } } here sopln is for system.out.println
12th Dec 2017, 11:01 AM
Shubh Mehrotra
Shubh Mehrotra - avatar
+ 2
Its too easy and like Krishna write, some languages can do it without any temporal variables https://code.sololearn.com/Wx5426M1Ok8W/?ref=app
15th Nov 2017, 1:39 PM
Daniel
Daniel - avatar
+ 2
suppose u have to swap a&b and a is 5 & b is 6 a = a+b // 11 b = a-b // 5 a = a-b // 6
15th Nov 2017, 1:57 PM
shobhit
shobhit - avatar
+ 1
Try always to do your own code and ask about doubts. We can practice one more time and learn something but you must to do your own tasks
15th Nov 2017, 1:40 PM
Daniel
Daniel - avatar
+ 1
# Using python a = 7 b = 5 a,b = b,a # result: a = 5 and b = 7
15th Nov 2017, 4:36 PM
#RahulVerma
#RahulVerma - avatar
0
Per @Krishna Teja Yeluripati's answer, if you are to swap integers in C outside of main(), it would require a pointer and/or a temporary variable. int swap(int *a, int *b) { //do this using temporary variable int tmp = *b; *b = *a; *a = tmp; // OR this using XOR // *a = *a ^ *b; // *b = *a ^ *b; // *a = *a ^ *b; } int main() { int x = 2; int y = 3; swap(&x, &y) printf("x is %i\ny is %i\n", x, y); } Output: x is 3 y is 2
16th Nov 2017, 12:04 AM
Chuma Umenze
- 1
import java.Util.* ..... ..... .... ..... ..... int a,b; a=b; b=a; sopln(a); sopln(b); } } here sopln is for system.out.println
15th Nov 2017, 3:45 PM
Shubh Mehrotra
Shubh Mehrotra - avatar