1.Swapping with using third variable : -
package com.tutorial4u;
public class SwapTwoNumber {
public static void main(String[] args) {
int n1 = 4;
int n2 = 5;
int temp;
System.out.println("Before swapping n1 = "+n1+" and n2
= "+n2);
temp = n1;
n1 = n2;
n2 = temp;
System.out.println("After swapping n1 = "+n1+" and n2
= "+n2);
}
}
Before
swapping n1 = 4 and n2 = 5
After
swapping n1 = 5 and n2 = 4
package com.tutorial4u;
public class SwapTwoNumber {
public static void main(String[] args) {
int n1 = 4;
int n2 = 5;
int temp;
System.out.println("Before swapping n1 = "+n1+" and n2
= "+n2);
n1 = n1+n2;
n1 = n1-n2;
n2 = n1=n2;
System.out.println("After swapping n1 = "+n1+" and n2
= "+n2);
}
}
Before swapping n1 = 4 and n2 = 5
After swapping n1 = 5 and n2 = 4
No comments:
Post a Comment