1.11M Members

Swap 2 number without using third variable

 
-1
 

Swap 2 number without using third variable

code do not use temp variable for swapping

if the code was useful please let me know

#include <stdio.h>
void main()
{
int a,b;
printf("enter number1: ie a");
scanf("%d",a);
printf("enter number2:ie b ");
scanf("%d",b);
printf(value of a and b before swapping  is a=%d,b=%d"a,b);
a=a+b;
b=a-b;
a=a-b;
printf(value of a and b after swapping  is a=%d,b=%d"a,b);
}
 
0
 

how bout this.


a=a+b;

b=a-b;

a=((a-b)/(-1));

 
-1
 

just a tricky way

#define SWAP(a, b)  do { a ^= b; b ^= a; a ^= b; } while ( 0 )
 
0
 

You would not even be able to compile the first code sample.

 
0
 

You would not even be able to compile the first code sample.

logic is imp

 
-1
 

this can be done using stack...........put the value of a and b in stack....then store first in b then in a.... as stack is first in last out....

 
0
 

For a newbie Zamansiz, you certainly have my vote of confidence.
-
Using 'tricks' and 'trickly subrt'ns is exactly what got Microsoft into so many buggy problems at the beginning.

- You are spot-on by laying this out in the beginning
and allowing the debugger see it right away.

- - Easy to spot - Easy to understand.

Shift-Stop

* by Newbie I am assuming that you're
New to coding
and not Ken Thompson, or D. Ritchie, or K. Knowlton.

 
-1
 
#include<stdio.h>
void main()
 {
   int a=10,b=20;
   printf("Variables Before swap\nA= %d \nB= %d",a,b);
   a=a+b;
   b=a-b;
   a=a-b;
   printf("\nVariables after swap\nA= %d \nB= %d\n",a,b);
 }
#include<stdio.h>
void main()
 { 
   int a=10,b=20;
   printf("Variables Before swap\nA= %d \nB= %d",a,b);
   a=a*b;
   b=a/b;
   a=a/b;
   printf("\nVariables after swap\nA= %d \nB= %d\n",a,b);
 }
#include<stdio.h>
void main()
 {
   int a=10,b=20;
   printf("Variables Before swap\nA= %d \nB= %d",a,b);
   a^=b;
   b^=a;
   a^=b;
   printf("\nVariables after swap\nA= %d \nB= %d\n",a,b);
 }
 
2
 

Method1
(The XOR trick) a ^= b ^= a ^= b;
Although the code above works fine for most of the cases, it tries to modify variable 'a' two times between sequence points, so the behavior is undefined. What this means is it wont work in all the cases. This will also not work for floating-point values. Also, think of a scenario where you have written your code like this

swap(int *a, int *b)
{
*a ^= *b ^= *a ^= *b;
}
Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the variable with itself). This scenario is quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be swapped are already equal to each other. swap(int *a, int *b) {
if(*a!=*b) { *a ^= *b ^= *a ^= *b; } }

Method2 This method is also quite popular a=a+b; b=a-b; a=a-b; But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this might end up giving you wrong results. Method3 One can also swap two variables using a macro. However, it would be required to pass the type of the variable to the macro. Also, there is an interesting problem using macros. Suppose you have a swap macro which looks something like this
#define swap(type,a,b) type temp;temp=a;a=b;b=temp;
Now, think what happens if you pass in something like this swap(int,temp,a) //You have a variable called "temp" (which is quite possible). This is how it gets replaced by the macro
int temp;
temp=temp;
temp=b;
b=temp;
Which means it sets the value of "b" to both the variables!. It never swapped them! Scary, isn't it? So the moral of the story is, dont try to be smart when writing code to swap variables. Use a temporary variable. Its not only fool proof, but also easier to understand and maintain.

 
-3
 

haii this code also works to swap two numbers


if a=5,b=4
then a=(a+b)-(b=a);
also works

 
-1
 

it can be like this

#include<stdio.h>
#include<conio.h>
int main()
{
int i,j;
printf("enter the two variables:");
scanf("%d%d",&i,&j);
printf("before swap:First Var.=%d\tSecond Var.=%d\n",i,j);
i=i+j;
j=-(j-i);
i=-(i-j);
printf("After Swap: First Var.=%d\tSecond Var,=%d\n",i,j);
getch();
return 0;
}
 
0
 

And why would you want to bother doing anything like this?

 
1
 

Crucify me if you like, but the simple answer is that you can't. Even the CPU's XCHG instruction uses a hidden TEMP. Yes, there are lots of tricks and kludges that get you most of the way there, but they ALL fail on some type of data or other. Besides, why in the world would anyone want the use additions, subtraction, multiplications and divisions (inefficient) rather than a simple MOVE instruction (very efficient) and suffer all the ills of truncation and round-off error? It's slower, uses more memory and is failure prone. On the other hand, creating a temp is either a Zero time operation (created at compile time) or a very fast creation on the Stack (one assembly instruction). Iven if the Temp needs to be created on the heap or in thread local storage, it's still probably faster. If you really need to optimize, the only guaranteed method is to use assembly - and even that may have issues of transportability. The only time I would ever consider this would be when swapping giant structures (or perhaps millions of small ones), and even then I would probably re-write the code model to use pointer swaps instead. Why move big chunks of data when you can simply swap a pointer?

Want a simple assembly language example?

Mov ECX, SizeOfVariableInBytes
Mov SI, AddressOfOneObject
Mov DI, AddressOfOtherObject

MLP:
    Mov AL,[ESI]
    Mov AH,[EDI]
    Mov [ESI],AH
    Mov [EDI],AL
    Inc ESI
    INC EDI
    Loop MLP

This is an untested skeleton, just showing the essentials. It is written in terms of bytes simply because it is bad technique to write an generic example for a certain data type in particular. It also assumes the use of 32 bit registers, and that the data is in the (default) Data Segment. It will only work with simple data types and structure, but will fail miserably on things like Class Instances.

If you are really a Hog for optimization, you could shorten it to this:

    Mov ECX, SizeOfVariableInBytes
    Mov SI, AddressOfOneObject
    Mov DI, AddressOfOtherObject

    MLP:
        Mov AL,[ESI]
        XCHG AL,[EDI]
        Mov [ESI],AL
        Inc ESI
        INC EDI
        Loop MLP

Which uses the EXCH instruction to replace a pair of Mov Instructions. My opinion is that no optimizing compiler can do better than this, except perhaps when possible by moving words or double words and therefore fewer loop iterations. In fact, something like this is probably what the compiler would construct anyway.

 
0
 
#include<conio.h>
#include<stdio.h>

void Change_Address( int *&p, int *&pt)
{
     int *pp;
     pp = p;
     p = pt;
     pt= pp;
}
int main(void)
{
    int a =3, b = 4, *p, *p1;
    p = &a; p1 = &b;    
    printf("%d %d\n", *p, *p1);
    Change_Address(p, p1);
    printf("%d %d", *p, *p1);

    getch();     
    return 0;
}
 
0
 

void Change_Address( int *&p, int *&pt)

That's C++, not C.

 
0
 

Thanks for all of your answers..... But i have one doubt.
While swapping if overflow occurs how to manage it....?
Or else if any other solution is there to take care overflow also.

 
1
 

While swapping if overflow occurs how to manage it....?

Use a temporary variable of the same type, no overflow will occur in that situation. If you try using the arithmetic tricks, overflow is a risk and greatly increases the complexity of the swap for the negligible benefit of a few bytes saved memory. If you try using the XOR swap, swapping with self is a risk and slightly increases the complexity of the swap. XOR also demands that the swapped type be integral.

These tricks put undue restrictions on you, and the savings aren't worth it if you're writing a general purpose swap. So the answer is to just bite the bullet and use a temporary variable; they're not that expensive.

Don't try to be clever, write code that works.

 
0
 

These are applicable to programming in general (Python -> import this)

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

 
-1
 
import java.io.*;
class swap{
        public static void main(String args[]) throws IOException{
            BufferedReader br=new BufferedReader(new 

InputStreamReader(System.in));
            System.out.print("Enter 1st no: ");
            int x=Integer.parseInt(br.readLine());
            System.out.print("Enter 2nd no: ");
            int y=Integer.parseInt(br.readLine());
            System.out.println("\nNumbers Before Swapping:");
            System.out.println("x = "+x);
            System.out.println("y = "+y);
            //Swapping Method 4
           // x = y-x+(y=x);


            System.out.println("\nNumbers After Swapping:");
            System.out.println("x = "+x);
            System.out.println("y = "+y);
        }
}
 
0
 

While that may work in Java, it's horribly broken in C due to undefined behavior. Further, you've introduced a requirement to check for integer overflow.

For all of the mental gymnastics involved in devising ways to swap without a temporary (though these days everyone just Googles for solutions to look smart), nobody has come up with a general purpose solution that's even comparable to using a temporary, much less superior.

Finally, if you're micro-optimizing to this granularity, you've probably lost perspective as concerns performance and memory usage.

You
Post:
Start New Discussion
View similar articles that have also been tagged: