#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;
}
Swap a 2 number?
asked 3 months agoAsked
1Answers
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.