# I am a Mixed Drink

• ## Blog Stats

• 83,886 hits

• ## Top Posts

© Sriram and sriramchewsthefat, 2009. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to Sriram and sriramchewsthefat with appropriate and specific direction to the original content.

## A SIMPLE LOGIC FOR SWAPPING VALUES OF TWO VARIABLES WITHOUT USING TEMPORARY VARIABLE OR POINTER

Posted by sriramchewsthefat on May 29, 2009

Please note: The original url for this post is:

https://sriramchewsthefat.wordpress.com/
If you are reading this on any other web site, this content is stolen.

Hi,this time im going to write some techie stuffs.Just im going to explain the logic of Swapping the 2 nos without using temporary or TEMP variable,and also without using the pointers .This logic can be applied in all the programming languages.now im just going to explain the logic and i will give the example in c program as well as  java program and there outputs in this post.

IN DEPTH ANALYSIS ON LOGIC:

Logic’s synonym is ‘A system of reasoning’.so the logic will differ from person to person.But the end result(in our case OUTPUT) has to be same.Each person have their own way of thinking and writing the code,but it has to solve some criteria.So we have to use our brain in getting the solutions through logical thinking.The following figure will help you to understand the above discussion.

Enough to say about the ‘logic’ stuff.Let us go into solving this problem.

Question:

Swapping the values of 2 variables without using Temp variable and pointers.

Consider 2 variables as a and b.consider it as INTEGER.The following logic works well for all values of integer.

int a,b;

Get the values of a and b through user.

In C programming,use the following coding for getting the value from the user

printf(“Enter the values of A and B \n”);

scanf(“%d %d”,&a,&b);

In the 2nd line scanf() statement will be used for getting the values from the user.

REAL LOGIC IN THE PROGRAM:

Now the real logic of the program comes.we got the values of a and b.we have to swap the values.lets see the logic,

a=a+b;//line 1

b=a-b;//line 2

a=a-b;//line 3

printf(“after swapping the value of A is %d and B is %d  “,a,b);//line4

The line1,line2,line3 play an important role in this program.These lines are the LOGIC to get our solution.just u have to think in mind before writing this logic by assigning some values for a and b .

I assigned a’s value as 1 and b’s value as 2.some tips,always try to give some simple values while devising the logic of the program.

so i taken a=1 and b=2,

so line1 will become

a=a+b;//returns a=3   (a=1+2)

line 2 will give

b=a-b;//returns b=1 (because new value of a is 3 ,i.e b=3-2)

line 3 will return

a=a-b;//returns a=2 (because now b’s value is 1,i.e a=3-1)

Now see that the values of a and b are swapped.The line4 is used for printing the swapped values. This is the logic i think of when i used to find this solution and it will work for all the Integer values.But there are so many logic will be there to find this solution.If u know just post your logic in the comment.The full coding of this program is given below in 2 programming languages,

In C Programming Language:

/*A SIMPLE LOGIC FOR SWAPPING A TWO NOS WITHOUT USING TEMPORARY VARIABLE OR POINTER IN C*/

#include<stdio.h>

#include<conio.h>

main()

{

int a,b;

printf(“Enter the values of A and B \n”);

scanf(“%d %d \n”,&a,&b);

a=a+b;

b=a-b;

a=a-b;

printf(“after swapping the value of A is %d and B is %d  “,a,b);

}

Sample Output:

Enter the values of A and B

10 20

after swapping the value of A is 20 and B is 10

Notes:

Scanf() is used for getting the input value throgh keyboard

printf() is used for showing the output on the screen and shows the keyboard entered values through addresses of the variables.

REFERENCES:

If you are a beginner  in programming languages start with C.Yashwanth Kanithkar’s ‘LET US C’ is a good book for the beginners.

In Java Programming Language:

/*A SIMPLE LOGIC FOR SWAPPING A TWO NOS WITHOUT USING TEMPORARY VARIABLE  IN JAVA*/

/*NOTE:There was no pointer concept in Java*/

class Swapeg

{

public static void main(String args[])

{

int a,b;

a= Integer.parseInt(args[0]);

b= Integer.parseInt(args[1]);

System.out.println(“Initial value of a and b is “+ a +” and ” + b);

a=a+b;

b=a-b;

a=a-b;

System.out.println(“Swapped value of a and b is ” + a +” and ” + b);

}
}

Sample Output:

Intial value of a and b is  10 and 20

Swapped value of a and b is 20 and 10

Notes:

Integer.parseInt(arg[0]),,…Integer.parseInt(arg[n]),works like scanf() statement (in c),used for getting the input from the user.Here arg[0] represent the first command line input.

For any further reference in java:

Use ‘ java complete reference’ written by HERBERT SCHILDT.for any references and through web,see the links i have given under technical stuff catergory.

The following content has been added on  04-07-2009.

Im going add some codes in this section, because it seems the above codes will create temporary storage for storing the intermediate values of  a and b.Whenever we use the + or – operator, a temporary is created.This temp problem can be fixed by using += or -= in the program.I came to know this problem when Dan Mergens commented me  and he only gives the solution to this. The following logic can be used in the coding:

logic for swapping 2 nos without using temp in c or java:

a += b;
b -= a;
b *= -1;
a -= b;

The above logic credit should go to Dan Mergens.For further reference read the comments of him in this post.

I then tried out one logic and it works fine for me,the logic is simple.The nos have been swapped within a single line of statement and i have not used any temporary variable.The logic is

Swapping or swap 2 nos without using temp in a single line:

b=b+a-(a=b);

Note:

We can use the above two logics instead of

a=a+b;

b=a-b;

a=a-b;

its upto you to decide.But all the above logics will work fine

caveats:(caution)

*The range of integer data type is -2,147,483,648 to 2,147,483,647

*if the entered value is not within the range then java while compilation time will show the following error,

Example if one of the value is -2147483649 :

Exception in thread “main” java.lang.NumberFormatException: For input string: “-2147483649”
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)

for further details to know about How the range and the values are calculated in java or c see the following link…

https://sriramchewsthefat.wordpress.com/2009/06/25/how-the-range-and-values-of-primitive-data-types-in-javaor-c-or-c-have-been-calculated/

P.S: I took the images from

please note that i didnt notice that this images is having copyright or not.So pardon me if i have used the copyrighted images.so im not having any copyright over the images i used in this post.

Hopefully you like this post.feel free to comment.cheers!!

### 14 Responses to “A SIMPLE LOGIC FOR SWAPPING VALUES OF TWO VARIABLES WITHOUT USING TEMPORARY VARIABLE OR POINTER”

Dai Super da…Sriram is starting to become a True Professional…Great Work carry on the Good work

• ### sriramchewsthefatsaid

Thanks sesha for your comments,i will always try to write some good posts..cheers

2. ### Visusaid

Hey scene da machi!! 🙂 … Keep going.. 🙂
But nee enna thaan program potaalam S**ESH maari aaga mudiyadhu pa!! 😛

3. ### AVsaid

I think this will be useful for freshers like us when we were in the first year da. Nice post da. It will be useful for those who really like programming and have more interest in it 😀

4. ### Dan Mergenssaid

The point of this exercise was to copy the values without use of a temporary, however instead of creating one: int temp = a, a=b, b=temp; you create three a=a+b, b=a-b, and a=a-b; Note that whenever you use the + or – operator, a temporary is created. This can be fixed by using the += and -= operators (I speak for C; I imagine the same holds true for Java.)

a += b;
b -= a;
b *= -1;
a -= b;

Note also, you should always explain the caveat that goes along with this, namely, if you exceed the boundaries of the type (in this case ‘int’), it is unknown how the compiler will process the addition and subtraction over the boundary, and the result may not be as expected.

• ### sriramchewsthefatsaid

Thanks Dan for reading my post,and giving this valuable comment,i will update my post with the above program and also i will explain the caveats of the program.I also found out that we can swap 2 variables in single line.I think the following line didnt create any temporary variable,

b=b+a-(a=b);

i think the above line works fine for all values it seems, and i will update the post soon..once again thanks for your worthful comments,cheers

5. ### phoxissaid

none of these techniques are proper, and good, each of them has drawbacks, the arithmetic one is a subject to overflow, floating point is not supported by the bitwise solution. And again another thing is the arithmetic solution does three math operations and three assignment, in comparison the three variable method does onlt three assignments, which significantly speeds up the code , when it is being executed a lot of times. So we do not achieve anything by saving 1 variable allocated, instead we loose program stability and portability.

But these techniques are worth knowing when learning C Programming , (or others), but better not use them.

6. ### Nishasaid

Hai frrnd…… This program is very useful for me also i gathered lot of excellent points….. Thank u….

7. ### gayathrisaid

ur upload ws really usefull 4 me…..am a fresher -1 yr BE student…..tq……

8. ### Pooja.B.M.said

I’m glad that my problom solved with the help of you…………..! THANK YOU

9. ### pavansaid

Hi ,Nice post it helps a lot for new learners.