wu :: forums (http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi)
riddles >> cs >> Swapping of two variable without third variable C
(Message started by: adamblack on Feb 3rd, 2012, 1:49am)

Title: Swapping of two variable without third variable C
Post by adamblack on Feb 3rd, 2012, 1:49am


//swapping without third variable
//A tricky way of swapping
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20;
clrscr();
printf("Before swapping:\na=%d\nb=%d",a,b);
a=b+a;
b=a-b;
a=a-b;
printf("\nAfter swapping:\na=%d\nb=%d",a,b);
getch();
}

Title: Re: Swapping of two variable without third variabl
Post by Grimbal on Feb 3rd, 2012, 2:28am
OK, as a little puzzle "how to swap variables without extra space", this is one solution.

But as a programming trick, I wouldn't use it.  It is less readable and is likely to be a bit slower than the standard method using a temporary variable.

Title: Re: Swapping of two variable without third variabl
Post by adamblack on Feb 3rd, 2012, 2:36am
yes you are right

this question was asked to me in my interview to check my IQ but i could not solve it at that time. i took about 30 min when i came out.



i would like to know if you have any other technique to  do this.
also would like question like it.............

------------------------------------------------

(link removed by moderator)

Title: Re: Swapping of two variable without third variabl
Post by Grimbal on Feb 3rd, 2012, 2:41am
Another classical way is:
a ^= b;
b ^= a;
a ^= b;

BTW, links to irrelevant web sites are against this forum's netiquette.

Title: Re: Swapping of two variable without third variabl
Post by adamblack on Feb 3rd, 2012, 2:45am
sure thanks

Title: Re: Swapping of two variable without third variabl
Post by phpsomkumar on Mar 29th, 2012, 9:45pm

#include<stdio.h>
#include<conio.h>
void main()
{
int x=10,y=20;
clrscr();
printf("Before swapping:\nx=%d\ny=%d",x,y);
x=y+x;
y=x-y;
x=x-y;
printf("\nAfter swapping:\nx=%d\ny=%d",x,y);
getch();
}

Title: Re: Swapping of two variable without third variabl
Post by phpsomkumar on Mar 29th, 2012, 9:49pm
<?php

$x = 10;

$y = 20;
$x = $x+$y;
$y = $x – $y;
$x = $x – $y;
?>



Powered by YaBB 1 Gold - SP 1.4!
Forum software copyright © 2000-2004 Yet another Bulletin Board