xxxxxxxxxx
a=20;
b=40;
a=a+b;
b=a-b;
a=a-b;
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
using System;
class MainClass {
public static void Main (string[] args) {
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
Console.WriteLine("After swapping: num1 = "+ num1 + ", num2 = " + num2);
Console.ReadLine();
}
}
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);
}