Dremendo Tag Line

Swap numbers without using third variable in C++

cin - Question 10

In this question, we will see how to input two integers into two variables x and y in C++ programming using the cin statement and swap their values without using a third variable. To knowTo know more about cin statement click on the cin statement lesson.

Q10) Write a program in C++ to input two integers into two variables x and y and swap their values without using a third variable.

x = 5
y = 3

After Swap
x = 3
y = 5

Program

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    int x,y;
    cout<<"Enter value of x ";
    cin>>x;
    cout<<"Enter value of y ";
    cin>>y;
    x=x+y;
    y=x-y;
    x=x-y;
    cout<<"After Swap\n";
    cout<<"x="<<x<<endl;
    cout<<"y="<<y;
    return 0;
}

Output

Enter value of x 10
Enter value of y 20
After Swap
x=20
y=10
video-poster