+ 9

C program for Swapping two numbers

10th Nov 2016, 5:06 AM
David Kariuki
David Kariuki - avatar
8 Antworten
+ 8
Swapping two numbers #include < stdio.h > int main() {   int x, y, temp;   printf("Enter the value of x and y\n");   scanf("%d%d", &x, &y);   printf("Before Swapping\nx = %d\ny = %d\n",x,y);   temp = x;   x = y;   y = temp; /*using temp to swap storing x to temp and y to x then moving temp to y*/   printf("After Swapping\nx = %d\ny = %d\n",x,y);   return 0; }
10th Nov 2016, 5:07 AM
David Kariuki
David Kariuki - avatar
+ 2
if yiu don't want use a third variable temp try this one instead /* same code */ a=a+b; b=a-b; a=a-b; /* same code */
17th Nov 2016, 11:47 AM
pasquale napolitano
pasquale napolitano - avatar
+ 2
You can also use this code using bitwise xor operator (^) a = a ^ b; b = a ^ b; a = a ^ b; I think this is the best way to swap 2 numbers
17th Nov 2016, 5:04 PM
Ishpreet Singh Bindra
Ishpreet Singh Bindra - avatar
+ 2
a=a+b-(b=a) this is a simple one line logic without using a third variable
18th Nov 2016, 3:19 AM
Bharath
0
{ int a,b; printf("enter number"); scanf("%d%d",&a,&b); a=a+b; b=a-b; a=a-b; printf("a=%d b=%d",a,b); }
18th Nov 2016, 5:20 PM
Rehan hussain
Rehan hussain - avatar
0
by using:- a=(a+b); b=(a-b); a=(a-b); swaps the two numbers.... if a=2; and b=10; then by using swaps method as mentioned above... a=10; and b=2;
19th Nov 2016, 3:24 AM
Arun Vishwakarma
Arun Vishwakarma - avatar
0
it can be done by more than 20 ways....
21st Nov 2016, 8:48 AM
Manthan
Manthan - avatar
0
Swapping two numbers #include < stdio.h > int main() {   int x, y;   printf("Enter the value of x and y\n");   scanf("%d%d", &x, &y);   printf("Before Swapping\nx = %d\ny = %d\n",x,y);   x=x+y; y=x-y; x=x-y; /*without using temp to swap storing x to temp and y to x then moving temp to y*/   printf("After Swapping\nx = %d\ny = %d\n",x,y);   return 0; }
20th Oct 2021, 11:45 AM
sree harsha
sree harsha - avatar