C++ Example – C++ program to Swap two numbers




cpp tutorials
cpp tutorials

Swapping numbers in C++ means exchanging the values of two C++ variables with each other.

C++ program to Swap two numbers using third variables.

#include <iostream>

using namespace std;

int main()
{
    int a,b,c;
    cout << "Enter value of a: ";
    cin >> a;
    cout << "Enter value of b: ";
    cin >> b;
    c=a;
    a=b;
    b=c;
    cout<<"After swaping a: "<< a << " b: " << b;
    return 0;
}

/*
OUTPUT:
Enter value of a: 5
Enter value of b: 3
After swaping a: 3 b: 5
*/

 

C++ program to Swap two numbers without using third variable

#include <iostream>

using namespace std;

int main()
{
    int a,b;
    cout<<"Enter value of a: ";
    cin>>a;
    cout<<"Enter value of b: ";
    cin>>b;
    a=a+b;
    b=a-b;
    a=a-b;
    cout<<"After swaping a: "<<a<<"b: "<<b;
    return 0;
}

/*
OUTPUT:
Enter value of a: 5
Enter value of b: 3
After swaping a: 3 b: 5
*/

 


Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





1 Comment

Leave a Reply

Your email address will not be published.


*