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:

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
Share.

I'm a full-stack developer, specializing in the PHP, JS, Wordpress, MEAN Stack, MERN Stack & Django. I hold a high standard of quality in everything that I do.

Leave A Reply