Tuesday, February 27, 2018

2 Ways to swap the values program in java [with / without third variable]


Swapping 2 variables  is one of the most common interview question asked in java interviews , Its very simple if one will use the third element and store the value in it and swapped the problem.but the main thinking starts when the interviewer asked you to tell him who to swap without using 3rd variable . In this post we will see both approach .

Approach 1: By Using third variable
Pseudo Code
  • We will take third variable , initialize the third element with 0
  • Store second variable value in third variable and store first variable value in second variable
  • Now store third variable value in first element and the value swapped.

Implementation


public class SwappingProgram {
 
 public static void main(String[] args) {
  int i =10 , j=15 ;
  
   System.out.println("Value of 'i' before swapping "+i+" value of 'j' before swapping "
      +j);
//  first method of swaping the value is to use the third element
  int k =0;
//  storing in third variable and swapping values
   k = j;
   j=i;
   i=k;
   
   System.out.println("Value of 'i' after swapping "+i+" value of 'j' after swapping "
     +j);
 }
 


}



Approach 2 Without using third variable
Pseudo Code
  • In this case , we first add both values and store it in first element.
  • Now as first element is the sum of both we will sub the j element from sum we will get value of initial i and store it in j value.
  • As a the value of j is now is value of i but now we need to get the value of j in I , we will subtract I from j we will store it in I , now we will get the value of j

Implementation


public class SwappingWithoutThirdVariable {
 
 public static void main(String[] args) {
  
  int i =-10 ,j=2;
   System.out.println("Value of 'i' before swapping "+i+" value of 'j' before swapping "
      +j);
//   using adding and sub to swap the values 
  i = i+j;
  j=i-j;
  i=i-j;
   System.out.println("Value of 'i' after swapping "+i+" value of 'j' after swapping "
      +j);
  
 }

}

I hope this article will help you , if you like this article please share it with your friends and colleagues .

Thanks for reading

0 comments:

Post a Comment