xxxxxxxxxx
let x = 1;
let y = 2;
[x, y] = [y, x]; // x = 2, y = 1
xxxxxxxxxx
// SWAPPING WITHOUT USING THIRD VARIABLE
#include<stdio.h>
int main()
{
int a=10, b=20;
printf("Before swap a=%d b=%d",a,b);
a=a+b;//a=30 (10+20)
b=a-b;//b=10 (30-20)
a=a-b;//a=20 (30-10)
printf("\nAfter swap a=%d b=%d",a,b);
return 0;
}
xxxxxxxxxx
// Another approach, that doesn't requires to create a third variable,
// but requires more computation
int a = 7;
int b = 2;
a = a ^ b;
b = a ^ b;
a = a ^ b;
// ^ means XOR
// if you want a more concise code, you can do
// a ^= b;
// b ^= a;
// a ^= b;
xxxxxxxxxx
public static void main(String[] args) {
int x = 10;
int y = 20;
int temp;
temp = x;
x = y;
y = temp;
System.out.println("x:"+x +" y:" + y);
}
xxxxxxxxxx
X= 25 (First number), Y= 23 (second number)
Swapping Logic:
X = X + Y = 25 +23 = 48
Y = X - Y = 48 - 23 = 25
X = X -Y = 48 - 25 = 23
and the numbers are swapped as X =23 and Y =25.
xxxxxxxxxx
var a=window.prompt('enter a number')var b=window.prompt('enter a number')var a=a+b;var b=a-b;var a=a-b;console.log ("value of a is",a);console.log('value of b is',b);
xxxxxxxxxx
//Swapping Using Addition and Subtraction(+ & -)
void swapping(int x, int y)
{
x = x + y; //1
y = x - y; //2
x = x - y; //3
printf("The values of a and b AFTER swapping are a = %d & b = %d \n", x, y);
}
//Swapping Using Multiplication and Division(* & /)
void swapping(int x, int y)
{
x = x * y; //1
y = x / y; //2
x = x / y; //3
printf("The values of a and b AFTER swapping are a = %d & b = %d \n", x, y);
}
//Swapping Using Bitwise XOR
void swapping(int x, int y)
{
x = x ^ y;
y = x ^ y;
x = x ^ y;
printf("The values of a and b AFTER swapping are a = %d & b = %d \n", x, y);
}
xxxxxxxxxx
//The code for a function to Swap two number with a temporary variable is as follows
#include<stdio.h>
void swapping(int, int); //function declaration
int main()
{
int a, b;
printf("Enter values for a and b respectively: \n");
scanf("%d %d",&a,&b);
printf("The values of a and b BEFORE swapping are a = %d & b = %d \n", a, b);
swapping(a, b); //function call
return 0;
}
void swapping(int x, int y) //function definition
{
int third;
third = x;
x = y;
y = third;
printf("The values of a and b AFTER swapping are a = %d & b = %d \n", x, y);
}