Swapping of two numbers is a classic programming exercise that helps build understanding of variable assignments and memory handling. In Dart, a modern and concise programming language developed by Google, this task can be performed in several ways.
In this post, we’ll cover
- Swapping with a temporary variable
- Swapping without a temporary variable
- Swapping using XOR Bitwise Operator
Swapping Of Two Numbers in Dart
Getting Started
Swapping of two numbers is a fundamental concept in programming, and Dart—being a modern, object-oriented language—provides several ways to accomplish this. Whether you're a beginner learning Dart or a seasoned developer revisiting the basics, understanding different techniques for swapping values can be helpful in day-to-day coding tasks.
Swapping two numbers means exchanging their values. For example, if a = 5 and b = 10, after swapping, a should be 10 and b should be 5.
This operation is often used in sorting algorithms, data manipulation, or solving logic-based problems.
Swap Two Numbers with Temporary Variable (Third Variable)
This is the most common, straightforward, popular and safest method in terms of readability and avoiding overflow errors.
void main() {
int x = 5;
int y = 10;
print("Value of x and y before swxpping $x and $y");
int temp = x;
x = y;
y = temp;
print("Value of x and y after swxpping $x and $y");
}
Output
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5
Swap Two Numbers Without Third Variable
This method avoids using extra memory by applying basic arithmetic.
void main() {
int x = 5;
int y = 10;
print("Value of x and y before swxpping $x and $y");
x =x+ y;
y = x-y;
x=x-y;
print("Value of x and y after swxpping $x and $y");
}
Output
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5
Swap Two Numbers Using XOR Bitwise Operator
This is a clever trick using XOR, which is especially useful in low-level or performance-critical code.
void main() {
int a = 5;
int b = 10;
print("Before swapping: a = $a, b = $b");
a = a ^ b;
b = a ^ b;
a = a ^ b;
print("After swapping: a = $a, b = $b");
}
Output
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5
Summary
Swapping values is an elementary yet powerful operation. Dart provides flexibility to implement it in various ways. Choose the method that best suits your needs depending on readability, performance, and context.
Thanks