Two Numbers Can Be Swapped Using The Third Variable In C++

Here, we’ll look at a program that uses a temporary third variable to swap two numbers. Following are the steps:
1. The first and second numbers’ values must be entered by the user. Both the first(num1) and second(num2) variables contain the input values.
2. Giving the third variable the first variable’s value.
3. Giving the first variable the value of the second variable.
4. Giving the second variable the third variable’s value.

A program to swap two numbers is an example.

#include <iostream>
using namespace std;

int main()
    int num1, num2, temp;
    cout<<"Enter 1st Number: "; 
    cout<<"Enter 2nd Number: "; 

    //displaying numbers before swapping
    cout<<"Before Swapping: First Number: "<<num1<<" Second Number: "<<num2;


    //displaying numbers after swapping
    cout<<"\nAfter Swapping: First Number: "<<num1<<" Second Number: "<<num2;
    return 0;


C++ Swapping Numbers

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button