Below is the program for swapping variables without any extra variable.

``````#include "stdio.h"
#include "conio.h"
void main()
{
int a=7;b=5;
clrscr();
a=a+b;
b=a-b;
a=a-b;
getch();
}``````

[CODE=c]a=a+b;
b=a-b;
a=a-b;[/CODE]
Will indeed swap to variables without a temp. Notice that you have to make sure that a+b does not exceed the maximum allowed integer. There is another way of swapping the variables without these constraints:
[CODE=c]void swap (int x, int y)
{
if (x != y)
{

Below is the program for swapping variables without any extra variable.

May I suggest that you view for example [URL="http://www.daniweb.com/forums/post1115685.html#post1115685"]this thread[/URL] ;)

## All 7 Replies

``````a=a+b;
b=a-b;
a=a-b;``````

Will indeed swap to variables without a temp. Notice that you have to make sure that a+b does not exceed the maximum allowed integer. There is another way of swapping the variables without these constraints:

``````void swap (int *x, int *y)
{
if (x != y)
{
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}``````

>> Below is the program for swapping variables without any extra variable.

May I suggest that you view for example this thread ;)

commented: Yes, thanks for pointing that out! +5

hai friend
this code also pretty works to swap two numbers without using a temporary variable and also is the code for swapping two numbers using a single line code

``````void main()
{

int a=5,b=8;
printf("before swap %d  %d",a,b);
b=(a+b)-(a=b); //swapping code
printf("after swap %d %d",a,b);

}``````

Very nice work sharagh.satya

thanks mr..
and sorry for saying you spelled my name wrong

Sorry

If I am not mistaken, that is the xor method no?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.