Swap Values using swap() in C++

This C++ program swaps values using swap() algorithm. The elements are passed to the function as parameters by reference and the values of the elements are then swapped by the function swap() defined in algorithm library.

Here is the source code of the C++ program which swaps values using swap() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to swap values using swap() algorithm
  3.  */
  4. #include <iostream>
  5. #include <algorithm>
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.     int A = 10, B = 20;
  11.  
  12.     cout << "Before swap" << endl;
  13.     cout << "A = " << A << ", B = " << B << endl;
  14.     swap(A, B);
  15.     cout << "After swap" << endl;
  16.     cout << "A = " << A << ", B = " << B << endl;
  17. }

$ a.out
Before swap
A = 10, B = 20
After swap
A = 20, B = 10

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.