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.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest 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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.