How do you swap two values? Provide a few examples.
How do you swap two values? Provide a few examples.
Swapping two values refers to the process of exchanging the values of two variables. There are several methods to achieve this in programming, and the approach can vary depending on the programming language and specific requirements. Here are a few examples of how to swap two values:
The most common and straightforward method to swap two values is by using a temporary variable. This method is language-agnostic and can be used in almost any programming language.
int a = 10, b = 20, temp;
temp = a; // Store the value of 'a' in 'temp'
a = b; // Assign the value of 'b' to 'a'
b = temp; // Assign the value of 'temp' (original 'a') to 'b'
Another method to swap two values is by using arithmetic operations such as addition and subtraction without using a temporary variable. However, this method is limited to numeric values and can lead to overflow issues with large integers or loss of precision with floating-point numbers.
int a = 10, b = 20;
a = a + b; // 'a' becomes 30
b = a - b; // 'b' becomes 10 (original value of 'a')
a = a - b; // 'a' becomes 20 (original value of 'b')
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.