0
Write program swap two number
8 Réponses
+ 18
C/C++/Java/JavaScript/C#
temp = a
a = b
b = temp
Python/Ruby
a, b = b, a
+ 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
+ 2
Its too easy and like Krishna write, some languages can do it without any temporal variables
https://code.sololearn.com/Wx5426M1Ok8W/?ref=app
+ 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
+ 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
+ 1
# Using python
a = 7
b = 5
a,b = b,a
# result: a = 5 and b = 7
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
- 1
import java.Util.*
.....
.....
....
.....
.....
int a,b;
a=b;
b=a;
sopln(a);
sopln(b);
}
}
here sopln is for system.out.println