Problem:
Exchange the values of two variables without using temporary variable.
Algorithm:
1. Get the values of a and b.
2. Calculate the sum of a and b and assign to a.
3. Calculate the difference of a and b and assign to b.
4. Calculate the difference of a and b and assign to a.
5. Print the values.
Solution:
import java.util.Scanner;
public class ExchangeTwoValuesWithoutUsingTempVariable {
static int a,b;
public static void main(String[] args) {
getTheValues();
System.out.println("Before exchange the values are " + a + " " + b);
exchangeValues();
System.out.println("After exchange the values are " + a + " " + b);
}
private static void getTheValues(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the value of a: ");
a = s.nextInt();
System.out.println("Enter the value of b: ");
b = s.nextInt();
}
private static void exchangeValues(){
a= a+b;
b = a -b;
a= a-b;
}
}
Output:
Enter the value of a:
30
Enter the value of b:
3
Before exchange the values are 30 3
After exchange the values are 3 30
Exchange the values of two variables without using temporary variable.
Algorithm:
1. Get the values of a and b.
2. Calculate the sum of a and b and assign to a.
3. Calculate the difference of a and b and assign to b.
4. Calculate the difference of a and b and assign to a.
5. Print the values.
Solution:
import java.util.Scanner;
public class ExchangeTwoValuesWithoutUsingTempVariable {
static int a,b;
public static void main(String[] args) {
getTheValues();
System.out.println("Before exchange the values are " + a + " " + b);
exchangeValues();
System.out.println("After exchange the values are " + a + " " + b);
}
private static void getTheValues(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the value of a: ");
a = s.nextInt();
System.out.println("Enter the value of b: ");
b = s.nextInt();
}
private static void exchangeValues(){
a= a+b;
b = a -b;
a= a-b;
}
}
Output:
Enter the value of a:
30
Enter the value of b:
3
Before exchange the values are 30 3
After exchange the values are 3 30
Very good post
ReplyDeletehttp://techinfobi.blogspot.in/
This will work provided a + b is less than Integer.MAX_VALUE(2147483647). You need to check whether it is so or not. If it is not, use BigInteger class.
ReplyDeleteif((a+b) <= Integer.MAX_VALUE) {
//proceed as it is mentioed
} else {
//use BigInteger
}
Similarly need to check a - b