Wednesday, 30 January 2013

Write a program to Swap two variables or number

The interchanging in nature is necessary to get achieve some task. In computer science we have a term called swapping or interchanging the positions of variable in which they mutually exchange from one value of variable to other variable value. This is usually done with the data in computer memory. For example, consider a variable A and B having value stored in them as A=11 and B=22 now it is not easy as we do in our imagination by interchanging values. In computer if you need manage memory to get this task to be done. Many of the programming languages have built in swap function. There are varies method to achieve this task and we have tried our maximum effort to show almost all version of swapping two variables.  

    1)  Using a temporary variable
This method is widely used and most popular way to swapping two numbers or variables. When we say temporary variable then it mean that we consuming extra memory in computer although this is not  a problem in most of the applications (it all depends on size of the values which are being swapped may occupy a lot of memory ). Now lets look at the java program to swap two integers using temporary variable.

Method 1:

 import java.util.Scanner;  
 class swap1  
 public static void main(String args[])  
 int x, y, temp;  
 System.out.println("Enter x and y");  
 Scanner in = new Scanner(;  
 //TO know about above line refer this  Java program to get input from user  
 x = in.nextInt();  
 y = in.nextInt();  
 System.out.println("Before Swapping\nx = "+x+"\ny = "+y);  
 temp = x;  
 x = y;  
 y = temp;  
 System.out.println("After Swapping\nx = "+x+"\ny = "+y);  
Method 2:
The given below method used pointer based approach and the it is implemented in C programming language.

 #include <stdio.h>  
 int main(void)  
   int a=11,b=22;  
   int *ptra,*ptrb;  
   int *temp;  
   printf("Before swapping: a = %d, b=%d",a,b);  
   ptra = &a;  
   ptrb = &b;  
   temp = ptra;  
   *ptra = *ptrb;  
   *ptrb = *temp;  
   printf("\nAfter swapping: a = %d, b=%d",a,b);  
   return 0;  
Method 3:
C program to swap two numbers using function

 void swap(int *,int *);  
 int main()  
   int a=11,b=22;  
   printf("Values before swap : a = %d, b=%d",a,b);  
   swap(&a,&b);// call swap function  
   printf("\nValues after swap : a = %d, b=%d",a,b);  
   return 0;  
 void swap(int *a,int *b){  
   int *temp;  
   temp = a;  

For Next version of  swapping methods click here..
(Here you can find almost all methods of swapping)

No comments:
Write comments

Featured post

List of Universities in Karnataka offering M.Sc Computer Science

The post-graduate programme in Computer Science (M.Sc Computer Science) contains two academic years duration and having a four semesters....

Popular Posts

Copyright @ 2011-2016