Swap a 2 number?

clock icon

asked 3 months agoAsked

message

1Answers

eye

7Views

The issue with swapping two numbers is that when you assign the value of one number to another, you risk losing the original value. For example, if you try to assign the value of `b` to `a`, then the original value of `a` is overwritten and lost. Without an extra variable or a clever operation, it's challenging to preserve both values while making the exchange.

 

The challenge is to ensure that both numbers can be swapped without losing any information, especially when you don't have extra memory (like a temporary variable) available.

1 Answers

#include <iostream>

// Function to swap two integers
void swap(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 5, y = 10;

    std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;

    swap(x, y);

    std::cout << "After swap: x = " << x << ", y = " << y << std::endl;

    return 0;
}

Write your answer here

Top Questions