[C/C++] Swap 2 Variable Without Using Third Variable

Program to swap 2 variable values 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

C 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;
}

C++ Code

#include <iostream>

using namespace std;

int main()
{
 int var1, var2;
 
 cout << "Enter value for first integer: ";
 cin >> var1;
 
 cout << "Enter value for second integer: ";
 cin >> var2;
 
 cout << "\nValues Before swapping" << endl;
 cout << "First Integer: " << var1 << endl;
 cout << "Second Interger: " << var2 << endl;
 
 var1 = var1+var2;
 var2 = var1-var2;
 var1 = var1-var2;
 
 cout << "\nValues After swapping" << endl;
 cout << "First Integer: " << var1 << endl;
 cout << "Second Interger: " << var2 << endl;
 
 return 0;
}

Output:

Swapping-without-Using-Third-Variable

Other Related Search Terms

  1. C Program to swap 2 variables without using third variable
  2. C++ program to swap 2 variables without  using temp variable
  3. C and C++ program for swapping 2 variables without  using third variable

Categories: C Language,C Programs,Computer Science

Tags: ,,

Leave A Reply

Your email address will not be published.

×