1,105,263 Community Members

Swap 2 number without using third variable

Member Avatar
vijaykrishnabor
Newbie Poster
20 posts since Apr 2010
Reputation Points: -7 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-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);
}
Member Avatar
haranaboy
Light Poster
34 posts since Sep 2010
Reputation Points: 2 [?]
Q&As Helped to Solve: 5 [?]
Skill Endorsements: 0 [?]
 
0
 

how bout this.


a=a+b;

b=a-b;

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

Member Avatar
Zamansiz
Newbie Poster
1 post since Oct 2010
Reputation Points: -4 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-1
 

just a tricky way

#define SWAP(a, b)  do { a ^= b; b ^= a; a ^= b; } while ( 0 )
Member Avatar
niehaoma
Newbie Poster
14 posts since May 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
vijaykrishnabor
Newbie Poster
20 posts since Apr 2010
Reputation Points: -7 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

logic is imp

Member Avatar
Tarang
Newbie Poster
3 posts since Jun 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-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....

Member Avatar
Shift-Stop
Newbie Poster
11 posts since Oct 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
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.

Member Avatar
b1izzard
Junior Poster
118 posts since Jun 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 14 [?]
Skill Endorsements: 0 [?]
 
-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);
 }
Member Avatar
DJSAN10
Posting Whiz in Training
260 posts since Dec 2010
Reputation Points: 28 [?]
Q&As Helped to Solve: 27 [?]
Skill Endorsements: 0 [?]
 
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.

Member Avatar
sharathg.satya
Posting Whiz in Training
265 posts since Oct 2010
Reputation Points: -10 [?]
Q&As Helped to Solve: 5 [?]
Skill Endorsements: 0 [?]
 
-2
 

haii this code also works to swap two numbers


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

Member Avatar
AL ZARRAR
Newbie Poster
1 post since Jun 2011
Reputation Points: -4 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-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;
}
Member Avatar
WaltP
Posting Sage w/ dash of thyme
9,363 posts since May 2006
Reputation Points: 2,905 [?]
Q&As Helped to Solve: 1,151 [?]
Skill Endorsements: 45 [?]
Team Colleague
 
0
 

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

Member Avatar
sbesch
Junior Poster in Training
69 posts since Aug 2009
Reputation Points: 2 [?]
Q&As Helped to Solve: 9 [?]
Skill Endorsements: 0 [?]
 
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.

Member Avatar
kmsDhaliwal
Newbie Poster
1 post since Feb 2014
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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;
}
Member Avatar
deceptikon
Eternally Awesome
4,687 posts since Jan 2012
Reputation Points: 1,341 [?]
Q&As Helped to Solve: 686 [?]
Skill Endorsements: 104 [?]
Administrator
Featured
 
0
 

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

That's C++, not C.

You
Post:
Start New Discussion
Tags Related to this Article