Here are some interesting ways to swap numbers in C++

Here are some interesting ways to swap numbers in C++

1. Using a Temporary Variable: This method involves using a third variable to temporarily hold the value of one of the variables while swapping their values.

#include <iostream>
using namespace std;

int main()
{
    int a = 5;
    int b = 10;
    int temp;

    temp = a;
    a = b;
    b = temp;

    cout << "After swapping:" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    return 0;
}
        

2. Using Addition and Subtraction: Basic arithmetic operations can be used to swap values by adding and subtracting.

#include <iostream>
using namespace std;

int main()
{
    int a = 5;
    int b = 10;

    a = a + b;
    b = a - b;
    a = a - b;

    cout << "After swapping:" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    return 0;
}
        

3. Using Multiplication and Division: Similar to addition and subtraction method, but uses multiplication and division.

#include <iostream>
using namespace std;

int main()
{
    int a = 5;
    int b = 10;

    a = a * b;
    b = a / b;
    a = a / b;

    cout << "After swapping:" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    return 0;
}
        

4. Using Bitwise XOR: A common method in programming interviews, XOR operation efficiently swaps values without the need for a temporary variable.

#include <iostream>
using namespace std;

int main()
{
    int a = 5;
    int b = 10;

    a = a ^ b;
    b = a ^ b;
    a = a ^ b;

    cout << "After swapping:" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    return 0;
}
        

5.Using 'std::swap' from '<algorithm>':

#include <iostream>
#include <algorithm>
using namespace std;

int main() 
{
    int a = 5;
    int b = 10;

    swap(a, b);

    cout << "After swapping:" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    return 0;
}
        






要查看或添加评论,请登录

Kajanthan sureshkumar的更多文章

社区洞察

其他会员也浏览了