Program Discussion :: Basics
5 / 279
Write code for swapping two variables without using 3rd variable.
Answer:
#include
#include
# include
using namespace std;
main()
{
int a=10, b=20;
clrscr();
cout
Asked In ::
Language:

Rajsekaran
20 Jun, 2017 11:23 PM
<!DOCTYPE html>
<html>
<body>
<?php
function Swapping()
{
$x = 10; $y = 5;
echo "No's for swapping are: X=".$x." and Y= ".$y."<br/>";
// Code to swap 'x' and 'y'
$x = $x + $y ; // x now becomes 15
$y = $x - $y ; // y becomes 10
$x = $x - $y ; // x becomes 5
echo "No's for swapping are: X=".$x." and Y= ".$y."<br/>";
}
Swapping();
?>
</body>
</html>
Language:

Sharan
7 Jul, 2017 9:30 AM
#include<stdio.h>
#include<conio.h>
main()
{
int a=10, b=20;
clrscr();
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);
getch();
}
Language:

Varun
7 Jul, 2017 9:30 AM
#include<stdio.h>
#include<conio.h>
# include <iostream>
using namespace std;
main()
{
int a=10, b=20;
clrscr();
cout<<"Before swap is:"<<a<<"\t"<<b;
a=a+b;//a=30 (10+20)
b=a-b;//b=10 (30-20)
a=a-b;//a=20 (30-10)
cout<<"\nAfter swap" <<a<<"\t"<<b;
getch();
}
Language:

Siddhartha Paul
19 Jun, 2019 2:16 PM
import java.io.*;
public class Swap
{
public static void main(String []args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number 1: ");
int a=Integer.parseInt(br.readLine());
System.out.println("Enter number 2: ");
int b=Integer.parseInt(br.readLine());
System.out.println("Before swapping, number 1= "+a+" || number 2= "+b);
a=a^b;
b=a^b;
a=a^b;
System.out.println("After swapping, number 1= "+a+" || number 2= "+b);
}
}
Language:

Ravuri Maheshbabu
9 Dec, 2019 8:43 AM
x = 10
y = 5
# code to swap
# 'x' and 'y'
# x now becomes 50
x = x * y
# y becomes 10
y = x // y;
# x becomes 5
x = x // y;
print("After Swapping: x =", x, " y =", y);
Language:

Kumar
20 Aug, 2021 1:26 PM
a=int(input())
b=int(input())
a=a b
b=a-b
a=a-b
Language:

Kumar
20 Aug, 2021 1:26 PM
a=int(input())
b=int(input())
a=a b
b=a-b
a=a-b
Language:

Kumar
20 Aug, 2021 1:26 PM
a=int(input())
b=int(input())
a=a b
b=a-b
a=a-b
Language:

Kumar
20 Aug, 2021 1:26 PM
a=int(input())
b=int(input())
a=a b
b=a-b
a=a-b
Language:

Kumar
20 Aug, 2021 1:26 PM
a=int(input())
b=int(input())
a=a b
b=a-b
a=a-b
Language:

Kumar
20 Aug, 2021 1:26 PM
a=int(input())
b=int(input())
a=a b
b=a-b
a=a-b
Language:

Kumar
20 Aug, 2021 1:26 PM
a=int(input())
b=int(input())
a=a b
b=a-b
a=a-b
Language:

Kumar
20 Aug, 2021 1:26 PM
a=int(input())
b=int(input())
a=a b
b=a-b
a=a-b
Language:

Kumar
20 Aug, 2021 1:26 PM
a=int(input())
b=int(input())
a=a b
b=a-b
a=a-b
Language:

Kumar
20 Aug, 2021 1:26 PM
a=int(input())
b=int(input())
a=a b
b=a-b
a=a-b