Program to swap 2 variable values without using third variable

Logic for Swapping 2 Variables Without Using Third Variable

  1. Add both variables in 2nd variable
  2. subtract 1st from 2nd and store it in 1st
  3. subtract 1st from 2nd and store it in 2nd

Algorithm for Swapping 2 Variables Values Without Using Temp

Let A=5, B=50
A = A+B;
B = A-B;
A = A-B;

Code


#include <stdio.h>
#include <conio.h>

int main() {
 int var1, var2;
 
 printf("Enter value for first integer: ");
 scanf("%d", &var1);
 
 printf("Enter value for second integer: ");
 scanf("%d", &var2);
 
 printf("\nValues Before swapping\n");
 printf("First Integer: %d", var1);
 printf("\nSecond Interger: %d", var2);
 
 var1 = var1+var2;
 var2 = var1-var2;
 var1 = var1-var2;
 
 printf("\n\nValues After swapping\n");
 printf("First Integer: %d", var1);
 printf("\nSecond Interger: %d", var2);
 
 getch();
 return 0;
}

Output