Swap Two Numbers Without Temp in C++
Q. Write a C++ program for Swap Two Numbers without using temp variable.
#include<iostream>
using namespace std;
int main()
{
int x, y;
cout << "Enter two numbers: ";
cin >> x >> y;
cout << "Before swapping(interchange) the numbers x= " << x << " y= " << y << endl;
x=x+y;
y=x-y;
x=x-y;
cout << "After swapping(interchange) the numbers x= " << x << " y= " << y << endl;
return 0;
}
Q. Write an algorithm to Swap Two Numbers without using temp variable.
1. Start
2. Input two numbers `x` and `y`
3. Display the values of `x` and `y` before swapping
4. Perform swapping using arithmetic operations:
- Set `x = x + y`
- Set `y = x - y` (Here, y becomes the original value of x)
- Set `x = x - y` (Here, x becomes the original value of y)
5. Display the values of `x` and `y` after swapping
6. End
Quickly Find What You Are Looking For
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.
point.com