[C/C++] Program to Swap 2 Variable Using Third Variable

Program to swap 2 variable values using third variable

  1. Store value of 1st variable in third variable that is temporary
  2. Store value of 2nd variable in 1st variable
  3. Now store value of temp or third variable in 2nd

C Code

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

int main()
{
 int var1, var2, temp;
 
 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);
 
 temp = var1;
 var1 = var2;
 var2 = temp;
 
 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, temp;
 
 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;
 
 temp = var1;
 var1 = var2;
 var2 = temp;
 
 cout << "\nValues After swapping" << endl;
 cout << "First Integer: " << var1 << endl;
 cout << "Second Interger: " << var2 << endl;
 
 return 0;
}

Output:

Swapping-Using-Third-Variable

Other Related Search Terms

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

Categories: C Language,C Programs,Computer Science

Tags: ,,

Leave A Reply

Your email address will not be published.

×