c-programs-basics
We have seen how to swap two numbers in c using a third variable, now here we will learn the c program to swap two numbers without using a third variable.

Swapping of Two Numbers Without Using Third Variable

#include<stdio.h>
#include<conio.h>
void main()
{
 int a,b;
 clrscr();

 printf("\n Type any two numbers to swap:\n ");

 printf("\n A = ");
 scanf("%d",&a);

 printf("\n B = ");
 scanf("%d",&b);

 printf("\n Numbers before swapping \n");
 printf("\n A = %d \t B = %d",a,b);

 a=a+b;
 b=a-b;
 a=a-b;

 printf("\n\n Numbers after swapping\n");
 printf("\n A = %d \t B = %d",a,b);


getch();
}

Output :

Output-Swap-Two-Numbers-Without-Third-Variable














When we used a third variable we interchanged the values of variables and swapped the numbers. Here ,

  • we have added both the numbers (A and B) and stored the total in one of the variables(A). 
  • Then we subtracted both the numbers from the total one by one. 
  • When you subtract one number (A) from the addition of two numbers (A & B) we get the second number (B). 
  • Then we stored the values in appropriate variables to swap the values.

Dev C++ Program to Swap Two Numbers

#include<stdio.h>
int main()
{
 int a,b;
 
 printf("\n Type any two numbers to swap:\n ");

 printf("\n A = ");
 scanf("%d",&a);

 printf("\n B = ");
 scanf("%d",&b);

 printf("\n Numbers before swapping \n");
 printf("\n A = %d \t B = %d",a,b);

 a=a+b;
 b=a-b;
 a=a-b;

 printf("\n\n Numbers after swapping\n");
 printf("\n A = %d \t B = %d",a,b);

 getch();
return 0;
}
Output : 
Output-Swap-Two-Numbers-Without-Using-Third-Variable






In this way, we can swap to numbers in c without using a third variable.