Saturday 19 January 2013

Swapping Using 2 Variables

Some of mine friends asked me a question, the Question was
Agreed that we can swap two numbers using some math, but how can we swap two chars & string without using 3rd variable ?
This blog post will answer the question, the method i have used is preety simple & straight forward
We will do following swapping

  • Number Swapping
  • Chars Swapping 
  • Strings Swapping

To begin with lets quickly see the codes

  • Number Swapping
 void swappingNumbers( int a, int b ){
        System.out.println( "input value  a = " + a + "  b = " + b );
        a = a+b;
        b = a-b;
        a = a-b;
        System.out.println( "swapped values a = " + a + " " + " b = " + b );
    }


The above code swaps two ( signed & unsigned ) numbers without using any 3rd variable

  • Chars Swapping 
  •  void swappingChars(char a, char b ){
            System.out.println( "input value  a = " + a + "  b = " + b );
            int p = (int)a ,q = (int)b;
            p =  ( ( (int) p ) + ((int)q) ) ;
            q = ( ( (int) p ) - ((int)q) ) ;
            p = ( ( (int) p ) - ((int)q) ) ;
            System.out.println( "swapped values p = " +  ( (char)p) + " q = " + ((char)q) );
        }
    

The above code swaps 2 chars without using 3rd variable. Here using two variable i.e p & q we have swap the chars


  • String Swapping
  •  
    void swappingStrings(String str1, String str2){
            System.out.println( "input value  str1 = " + str1 + "  str2  = " + str2 );
            str2 = str1 + " " + str2;
            String[] split = str2.split(" ");
            str1 = split[1];
            str2 = split[0];
            System.out.println( "swapped values = str1 = " + str1 + " str2 = " + str2);
        }
    

The above code swaps 2 Strings without using 3rd variable.

Output



Hope this helps.



No comments:

Post a Comment