C++ program to swap two integers without using third variable - coderforcoders

Search

Wednesday, 13 March 2019

C++ program to swap two integers without using third variable

#include<iostream>
using namespace std;
class swapit{
public:
int a,b,temp;
void swapNumbers()
{
cout<<"Numbers before swapping \na = "<<a<<" b = "<<b<<endl;
a=a+b;
b=a-b;
a=a-b;
cout<<"Numbers after swapping \na = "<<a<<" b = "<<b<<endl;
}
};
int main()
{
swapit obj1;
cout<<"Enter value of a\n";
cin>>obj1.a;
cout<<"Enter value of b\n";
cin>>obj1.b;
obj1.swapNumbers();
cout<<endl;
return 0;
}


Output 1:
Enter value of a
23
Enter value of b
12
Numbers before swapping
a = 23 b = 12
Numbers after swapping
a = 12 b = 23

Output 2:
Enter value of a
10
Enter value of b
5
Numbers before swapping
a = 10 b = 5
Numbers after swapping
a = 5 b = 10

Output 3:
Enter value of a
5
Enter value of b
25
Numbers before swapping
a = 5 b = 25
Numbers after swapping
a = 25 b = 5



No comments:

Post a Comment