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 :
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 :