This post contains a total of 5+ CPP Program Examples with Source Code to Swap Numbers. All these programs to Swap Numbers are made using C++.
You can use the source code of these examples with credits to the original owner.
Related Posts
CPP Programs to Swap Numbers
1. By Amarjit Dhillon
Made by Amarjit Dhillon. Program to Swap number without 3rd variable. Source
Please Enter first number :1 Please Enter second number 2 you Enter first = 1 second =2 Now First = 2 Second = 1
#include <iostream>
using namespace std;
int main()
{
int first, second;
cout<< "Please Enter first number :" ;
cin >>first;
cout<< "Please Enter second number ";
cin>>second ;
cout<<"you Enter first = " <<first <<"\n second ="
<<second ;
first +=second ;
second = first -second ;
first =first -second ;
cout << "\nNow First = "<<first ;
cout <<"\n Second = " <<second ;
return 0;
}
2. By hatem-al-fahd
Made by hatem-al-fahd. C++ Program to Swap Numbers. Source
Before swapping. a = 5, b = 10 After swapping. a = 10, b = 5
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10, temp;
cout << "Before swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
temp = a;
a = b;
b = temp;
cout << "\nAfter swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
3. By Stylish Pathan
Made by Stylish Pathan. Program to swap numbers using Pointers. Source
7 5
#include <iostream>
using namespace std;
int swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5;
int y = 7;
swap(x,y);
cout<<x<<endl<<y;
return 0;
}
4. By Jahnavi Vempati
Made by Jahnavi Vempati. Source
3 4 4 3
#include <iostream>
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
a=a+b;
b=a-b;
a=a-b;
cout<<a<<" "<<b;
return 0;
}
5. By Yash Raj
Made by Yash Raj. Source
420 69
#include <iostream>
using namespace std;
int main() {
int a=69;
int b= 420;
a=a+b; b=a-b; a= a-b;
cout<< a << endl;
cout << b;
return 0;
}
6. By Vaishnavi
Made by Vaishnavi. Simple C++ Program to Swap two Numbers. Source
Swap two numbers : -- Input 1st number : 2 Input 2nd number : 3 before swapping the 1st number is : 3 After swapping the 2nd number is : 2
#include <iostream>
using namespace std;
int main() {
cout << "\n\n Swap two numbers :\n";
cout << "--\n";
int num1, num2, temp;
cout << " Input 1st number : ";
cin >> num1 ;
cout << " Input 2nd number : ";
cin >> num2;
temp=num2;
num2=num1;
num1=temp;
cout << " before swapping the 1st number is : "<< num1 <<"\n" ;
cout << " After swapping the 2nd number is : "<< num2 <<"\n\n" ;
return 0;
}