There are two ways to swap two numbers without using the third variable in the c language
#include int main() { int a=100, b=200; printf("Before swapping a=%d b=%d",a,b); a=a+b;//a=100 (100+200) b=a-b;//b=200 (300-200) a=a-b;//a=200 (300-100) printf("\nAfter swapping a=%d b=%d",a,b); return 0; }
Instead of above logic, you can also use
a = b - a;
b = b - a;
a = b + a;
#include int main() { int a=100, b=200; printf("Before swap a=%d b=%d",a,b); a=a*b; b=a/b; a=a/b; printf("\nAfter swap a=%d b=%d",a,b); return 0; }
To implement this logic in a single line, you can use
a = (a * b) / (b = a);
#include int main() { int a, b; printf("Enter two numbers: "); scanf("%d %d", &a, &b); a = a ^ b; b = a ^ b; a = a ^ b; printf("Numbers after swaping: %d %d", a, b); return 0; }
Output
Enter two numbers: 11 22
Numbers after swaping: 22 11
Please Login to Post the answer