- C program to swap two numbers without using third variable.
- Yes we can swap two variables without using third variable.
- We have four different ways to swap two numbers without using third variable.
- Lets see an example C program on how to swap two numbers without using third variable and without using function.
Program #1: Write a simple C program to swap two numbers without using third variable
- #include <stdio.h>
- #include <stdlib.h>
- int main(int argc, char *argv[])
- {
- int a,b;
- printf("Please enter two integer numbers to swap\n");
- scanf("%d%d",&a,&b);
- printf("before swapping\n");
- printf("a=%d\n",a);
- printf("b=%d",b);
- a=b+a;
- b=a-b;
- a=a-b;
- printf("\nafter swapping\n");
- printf("a=%d\n",a);
- printf("b=%d",b);
- getch();
- }
Output:
Program #2: Write a simple C program to swap two numbers without using third variable
- #include <stdio.h>
- #include <stdlib.h>
- int main(int argc, char *argv[])
- {
- int a,b;
- printf("Please enter two integer numbers to swap\n");
- scanf("%d%d",&a,&b);
- printf("before swapping\n");
- printf("a=%d\n",a);
- printf("b=%d",b);
- a=a+b-(b=a);
- printf("\nafter swapping\n");
- printf("a=%d\n",a);
- printf("b=%d",b);
- getch();
- }
Output:
- Please enter two integers numbers to swap
- 30
- 40
- before swapping
- a=30
- b=40
- after swapping
- a=40
- b=30
Program #3: Write a simple C program to swap two numbers without using third variable : call by value
- #include <stdio.h>
- #include <stdlib.h>
- int main(int argc, char *argv[])
- {
- int a=12, b=13;
- a=a^b;
- b=a^b;
- a=b^a;
- printf("a=%d\n",a);
- printf("b=%d",b);
- getch();
- }
Output:
- a=13
- b=12
Program #4: Write a simple C program to swap two numbers without using third variable : call by value
- #include <stdio.h>
- #include <stdlib.h>
- int main(int argc, char *argv[])
- {
- int a=12, b=13;
- a=b-~a-1;
- b=a+~b+1;
- a=a+~b+1;
- printf("a=%d\n",a);
- printf("b=%d",b);
- return 0;
- }
Output:
- a=13
- b=12
No comments