Swap Two Numbers in C++


Q. Write a C++ program for Swap Two Numbers using temp variable.

#include<iostream>    
using namespace std;
  
int main()
{    
	int x, y,t;
	cout << "Enter two numbers: ";
	cin >> x >> y;
	cout << "Before swapping(interchange)) the numbers x= " << x << " y= "  << y << endl;
	t = x;
	x = y;
	y = t;
	cout << "After swapping(interchange) the numbers x= " << x << " y= "  << y << endl;
    return 0;
} 

Q. Write an algorithm to Swap Two Numbers using temp variable.

 1. Start
2. Read two integer values `x` and `y` from the user.
3. Display the values of `x` and `y` before swapping.
4. Create a temporary variable `t`.
5. Assign the value of `x` to `t`.
6. Assign the value of `y` to `x`.
7. Assign the value of `t` to `y`.
8. Display the values of `x` and `y` after swapping.
9. End



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.