SWAPPING THE VARIABLES
We can achieve the swap in many ways in this blog .We will using two different way to achieve the concept swapping.
- there are :-
- 1.USING THIRD VARIABLE.
- 2.WITHOUT USING THIRD VARIABLE.
- 3.GETTING RUN TIME INPUT.
- First add the two assigned variable such as a and b .
- Then store the added value in c (third variable).
- assign the value for a is c-a. And assign the value for b is c-a.
1.USING THIRD VARIABLE
Fist create the variable declaration like ( a , b and c).Assign the value for a and b ,use the c as a temporary variable.
How its works ?
package swappro;
static int a=10,b=20,c;
public static void main(String args[]) {
System.out.println("Before swapping\n");
System.out.println("the value of a :"+a+"the value of b :"+b);
c=a+b;
a=c-a;
b=c-a;
System.out.println("\nAfter swapping \n");
System.out.println("the value of a :" +a +"the value of b :"+b);
}
}
OUTPUT
Before swapping
the value of a :10the value of b :20
After swapping
the value of a :20the value of b :10
2. WITHOUT USING THIRD VARIABLE
Fist create the variable declaration like ( a and b).
How its works ?
- First add the two assigned variable such as a and b ..
- assign the value for a is a+b. And assign the value for b is a-b .Then re-assign the value for a is a-b.
package swappro;
public class Swapiing {
static int a=10,b=20;
public static void main(String[] args) {
System.out.println("Before swapping\n");
System.out.println("the value of a :"+a+"the value of b :"+b);
a=a+b;
b=a-b;
a=a-b;
System.out.println("\nAfter swapping \n");
System.out.println("the value of a :"+a+"the value of b :"+b);
}
}
OUTPUT
Before swapping
the value of a :10the value of b :20
After swapping
the value of a :20the value of b :10
3.GET THE RUN TIME INPUTS
package swappro;
import java.util.Scanner;
public class Swapiing {
static int a=10,b=20,c;
public static void main(String[] args) {
Scanner ss=new Scanner(System.in);
System.out.println("ENTER THE VALUE OF a :");
a=ss.nextInt();
System.out.println("ENTER THE VALUE OF b :");
b=ss.nextInt();
System.out.println("Before swapping\n");
System.out.println("the value of a :"+a+"the value of b :"+b);
System.out.println("\nAfter swaping \n");
c=a+b;
a=c-a;
b=c-b;
System.out.println("\nAfter swapping \n");
System.out.println("the value of a :"+a+"the value of b :"+b);
}
}
OUTPUT
ENTER THE VALUE OF a :
20
ENTER THE VALUE OF b :
30
Before swapping
the value of a :20 the value of b :30
After swapping
the value of a :30 the value of b :20
.
No comments:
Post a Comment