Author |
Topic: Swapping of two variable without third variable C (Read 3926 times) |
|
adamblack
Newbie
Posts: 3
|
|
Swapping of two variable without third variable C
« on: Feb 3rd, 2012, 1:49am » |
Quote Modify
|
//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(); }
|
|
IP Logged |
|
|
|
Grimbal
wu::riddles Moderator Uberpuzzler
Gender:
Posts: 7527
|
|
Re: Swapping of two variable without third variabl
« Reply #1 on: Feb 3rd, 2012, 2:28am » |
Quote Modify
|
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.
|
|
IP Logged |
|
|
|
adamblack
Newbie
Posts: 3
|
|
Re: Swapping of two variable without third variabl
« Reply #2 on: Feb 3rd, 2012, 2:36am » |
Quote Modify
|
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)
|
« Last Edit: Feb 3rd, 2012, 5:17am by Grimbal » |
IP Logged |
|
|
|
Grimbal
wu::riddles Moderator Uberpuzzler
Gender:
Posts: 7527
|
|
Re: Swapping of two variable without third variabl
« Reply #3 on: Feb 3rd, 2012, 2:41am » |
Quote Modify
|
Another classical way is: a ^= b; b ^= a; a ^= b; BTW, links to irrelevant web sites are against this forum's netiquette.
|
|
IP Logged |
|
|
|
adamblack
Newbie
Posts: 3
|
|
Re: Swapping of two variable without third variabl
« Reply #4 on: Feb 3rd, 2012, 2:45am » |
Quote Modify
|
sure thanks
|
|
IP Logged |
|
|
|
phpsomkumar
Newbie
Posts: 2
|
|
Re: Swapping of two variable without third variabl
« Reply #5 on: Mar 29th, 2012, 9:45pm » |
Quote Modify
|
#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(); }
|
|
IP Logged |
|
|
|
phpsomkumar
Newbie
Posts: 2
|
|
Re: Swapping of two variable without third variabl
« Reply #6 on: Mar 29th, 2012, 9:49pm » |
Quote Modify
|
<?php $x = 10; $y = 20; $x = $x+$y; $y = $x – $y; $x = $x – $y; ?>
|
|
IP Logged |
|
|
|
|