Hi All,
Here I am tried swap two numbers using temporary variable also without temporary variable :)
public class swapTwoNos {
public static void main(String[] args){
// Using temporary variable for swapping two numbers
int var1=50;
int var2=100;
System.out.println("Using temporary variable for swapping two numbers");
System.out.println("");
System.out.println(" Before swapping numbers \n var1 :"+var1+" var2 :"+var2);
swap(var1,var2); // calling swap function for exchage the values
withoutTemp(var1,var2);
}
private static void swap(int var1, int var2) {
int temp =var1;
var1=var2;
var2=temp;
System.out.println("After swapping numbers with temporary variable \n var1 :"+var1+" var2 :"+var2);
}
private static void withoutTemp(int var1, int var2) {
System.out.println("Using temporary variable for swapping two numbers");
System.out.println("");
var1 = var1 + var2;
var2 = var1 - var2;
var1 = var1 - var2;
System.out.println("After swapping numbers without temporary variable \n var1 :"+var1+" var2 :"+var2);
}
}
output:
Using temporary variable for swapping two numbersBefore swapping numbers
var1 :1 var2 :2
After swapping numbers with temporary variable
var1 :2 var2 :1
Using without temporary variable for swapping two numbers
After swapping numbers without temporary variable
var1 :2 var2 :1
No comments:
Post a Comment