A Program to Swap two Numbers

In this example, we are giving a program to swap two numbers which are given by the user.


Program to swap two numbers:

  1. #include<iostream>
  2. using namespace std;
  3. int main() {
  4. double first, second, temp;
  5. cout << "Enter first number: ";
  6. cin >> first;
  7. cout << "Enter second number: ";
  8. cin >> second;
  9. // Value of first number assigned into temp
  10. temp = first;
  11. // Value of second is assigned to first
  12. first = second;
  13. // Value of temp is assigned to second
  14. second = temp;
  15. cout << "After swapping, first number = " << first << endl;
  16. cout << "After swapping, second number = " << second << endl;
  17. return 0;
  18. }

Output:

Enter first number: 53.3
Enter second number: 42.2

After swapping, first number = 42.2
After swapping, second number = 53.3