Custom Search

Saturday, 25 August 2012

Java Program to swap 2 numbers without using third variable, Write a program in Java for swapping values of two variable without using temporary variable


Java Program to swap 2 numbers without using third variable, Write a program in Java  for swapping values of two variable without using temporary variable


Program
class swapping
{
public static void main(String args[])
{
int no1,no2;
no1 = Integer.parseInt(args[0]);
no2 = Integer.parseInt(args[1]);
Logic L=new Logic();
L.swapping(no1,no2);
}
}
class Logic
{
public void swapping(int n1,int n2)
{
System.out.println("Before Swapping......");
System.out.println("No1 is: " + n1);
System.out.println("No2 is: " + n2);

n1 = n1+ n2; // Logic
n2 = n1 - n2;
n1 = n1 - n2;

System.out.println("After Swapping......");
System.out.println("No1 is: " + n1);
System.out.println("No2 is: " + n2);


}

}

No comments:

Post a Comment

Laptops