swapping of two numbers in java all possible models
MODEL:1/*Program to swap 2 values with third variable temp*/
class Swap
{
public static void main(String args[])
{
int a=1;
int b=2;
int temp=0;
System.out.println("Before swap: a="+a+"b="+b);
temp=a;
a=b;
b=temp;
System.out.println(" After swap: a="+a+"b="+b);
}
}
MODEL:2
/*Program to swap 2 values with out using third variable temp*/
class Swap
{
public static void main(String args[])
{
int a=1;
int b=2;
/*Program to swap 2 values without using the temporary variable and Arithmetic operators*/
class Swap
{
public static void main(String args[])
{
int a=1;
int b=2;
System.out.println("Before swap: a="+a+"b="+b);
a=a^b;
b=a^b;
a=a^b;
System.out.println(" After swap: a="+a+"b="+b);
}
}
MODEL:4
{
public static void Swap()
{
System.out.println("Before swap: a="+a+"b="+b);
temp=a;
a=b;
b=temp;
System.out.println(" After swap: a="+a+"b="+b);
}
}
MODEL:2
/*Program to swap 2 values with out using third variable temp*/
class Swap
{
public static void main(String args[])
{
int a=1;
int b=2;
int c=0;
System.out.println("Before swap: a="+a+"b="+b);
c=a;
a=b;
b=c;
System.out.println(" After swap: a="+a+"b="+b);
}
}
MODEL:3
System.out.println("Before swap: a="+a+"b="+b);
c=a;
a=b;
b=c;
System.out.println(" After swap: a="+a+"b="+b);
}
}
MODEL:3
/*Program to swap 2 values without using the temporary variable and Arithmetic operators*/
class Swap
{
public static void main(String args[])
{
int a=1;
int b=2;
System.out.println("Before swap: a="+a+"b="+b);
a=a^b;
b=a^b;
a=a^b;
System.out.println(" After swap: a="+a+"b="+b);
}
}
MODEL:4
/*Program to swap 2 values without using the temporary variable and third variable*/
class Swap{
public static void Swap()
{
int a=1;
int b=2;
System.out.println("Before swap: a="+a+"b="+b);
//add both the numbers and assign it to first
a=a+b;
b=a-b;
a=a-b;
System.out.println(" After swap: a="+a+"b="+b);
}
}
No comments:
Post a Comment