Swapping values between two variables is a common programming task. Here are examples of how to perform a swap in a few different programming languages:
Python
In Python, you can swap values directly using tuple unpacking:
# Initial values
a = 5
b = 10
# Swapping using tuple unpacking
a, b = b, a
print(f"a = {a}, b = {b}")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
In C, swapping values requires a temporary variable:
#include <stdio.h>
int main() {
int a, b, temp;
// Initial values
a = 5;
b = 10;
// Swapping using a temporary variable
temp = a;
a = b;
b = temp;
printf("a = %d, b = %d\n", a, b);
return 0;
}
Java
In Java, you can swap values using a temporary variable:
public class Swap {
public static void main(String[] args) {
int a = 5;
int b = 10;
// Swapping using a temporary variable
int temp = a;
a = b;
b = temp;
System.out.println("a = " + a + ", b = " + b);
}
}
JavaScript
In JavaScript, you can use destructuring assignment to swap values:
let a = 5;
let b = 10;
// Swapping using destructuring assignment
[a, b] = [b, a];
console.log(`a = ${a}, b = ${b}`);
C++
In C++, swapping can be done either using a temporary variable or the built-in std::swap function:
#include <iostream>
#include <algorithm> // for std::swap
int main() {
int a = 5;
int b = 10;
// Swapping using a temporary variable
int temp = a;
a = b;
b = temp;
std::cout << "Using temporary variable: a = " << a << ", b = " << b << std::endl;
// Swap back using std::swap
std::swap(a, b);
std::cout << "Using std::swap: a = " << a << ", b = " << b << std::endl;
return 0;
}
Ruby
In Ruby, you can use parallel assignment to swap values:
# Initial values
a = 5
b = 10
# Swapping using parallel assignment
a, b = b, a
puts "a = #{a}, b = #{b}"
Choose the language which you are most comfortable with, and the example should help you understand how to swap values in that language.