C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Program to swap two numbers without using the third variable
This program is to swap/exchange two numbers without using the third number in the way as given below: Example: Suppose, there are two numbers 25 and 23. Let 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. Algorithm
Java Program
import java.util.*;
class Swap
{
public static void main(String a[])
{
System.out.println("Enter the value of x and y");
Scanner sc = new Scanner(System.in);
/*Define variables*/
int x = sc.nextInt();
int y = sc.nextInt();
System.out.println("before swapping numbers: "+x +" "+ y);
/*Swapping*/
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swapping: "+x +" " + y);
}
}
Output: Enter the value of x and y 23 43 before swapping numbers: 23 43 After swapping: 43 23 C Program
#include<stdio.h>
int main()
{
int x, y;
printf("Enter the value of x and y?");
scanf("%d %d",&x,&y);
printf("before swapping numbers: %d %d\n",x,y);
/*swapping*/
x = x + y;
y = x - y;
x = x - y;
printf("After swapping: %d %d",x,y);
return 0;
}
Output: Enter the value of x and y? 13 22 before swapping numbers: 13 22 After swapping: 22 13 C# Program
using System;
class swap {
public static void Main()
{
Console.WriteLine("Enter the value of x and y");
int x=Convert.ToInt32(Console.ReadLine());
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("before swapping numbers: "+x +" "+ y);
/*swapping*/
x = x + y;
y = x - y;
x = x - y;
Console.WriteLine("After swapping: "+x +" " + y);
}
}
Output: Enter the value of x and y 213 432 before swapping numbers: 213 432 After swapping: 432 213 Python Program
x = int(input("Enter the value of x?"))
y = int(input("Enter the value of y?"))
print("before swapping numbers: %d %d\n" %(x,y))
#swapping#
x = x + y
y = x - y
x = x - y
print("After swapping: %d %d\n"%(x,y))
Output: Enter the value of x? 12 Enter the value of y? 24 before swapping numbers: 12 24 After swapping: 24 12 PHP Program<?php echo "Enter the value of x"; $x = readline(); echo "Enter the value of y"; $y = readline(); echo "before swapping numbers: "; echo $x; echo " "; echo $y; echo "\n"; /*swapping*/ $x = $x + $y; $y = $x - $y; $x = $x - $y; echo "After swapping "; echo $x; echo " "; echo $y; ?> Output: Enter the value of x 55 Enter the value of y 46 before swapping numbers: 55 46 After swapping 46 55
Next Topic#
|