Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Java-conversion Swapping of two numbers without using third variable

Related Tutorials


 
 

Share on Google+Share on Google+

Swapping of two numbers without using third variable

Advertisement
This tutorial will teach you the methods for writing program to swap of two numbers. Swapping is used where you want to interchange the values.

Swapping of two numbers without using third variable

In this tutorial we will learn about swapping of two number in java without using third variable. This is simple program to swap two value using arithmetic operation Swapping of two numbers is most popular question asked in so many interviews for fresher level.  Swapping is nothing but exchanging the value of  two variables. This is done by arithmetic operation on variables to exchange the value. From the example below you get the explanation in the following steps:

a=10
b=20
Step 1:  a = a+b //Now a has value 30
Step 2:  b = a-b //Now b has value 10
Step 3:  a = a-b //Now a has value 20
a=20 // Now a has value 20
b=10 // Now b has value 10

 Example : Using this example we will explain you how to swap two variables without using the third variables. First we declare one class in which we take two integer variables a and b. After initialization of two variables performing addition and subtraction on the variables to swap the value of both. So from the example below you can get the code.

import java.io.BufferedReader;
import java.io.InputStream;
public class Swapping {

	public static void main(String args[])
	{
		int a=10;
		int b=20;
		System.out.println("Value of a before swapping = "+a);
	        System.out.println("Value of b before swapping = "+b);
		a=a+b;// a has now value 30
	        b=a-b;// b has now value 10
	        a=a-b;// a has now value 20
	    
	       System.out.println("");
	       System.out.println("Value of a after swapping = "+a);
	       System.out.println("Value of b after swapping = "+b);
	}
}

Output from the program

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 24, 2013

Related Tutorials

Discuss: Swapping of two numbers without using third variable  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com