Have you ever had to swap two numbers in C without using any extra variable? Well, it’s the common case when you work under low memory or even when you are just making an attempt to code efficiently.
C Program to swap two numbers without using third variable is not just another coding trick but a good way to equip us with the skills to work on our code efficiently and resourcefully.
So, why is it even important? Because we need to think outside the box.
When not using an extra variable, one is pushed towards creative solutions. It is a trick in itself, which is often asked in coding interviews.
Method 1: Swapping Two Numbers Using Addition and Subtraction
This is one of the simplest ways of swapping two numbers without a third variable. It uses basic arithmetic operations of addition and subtraction.
Here’s how it works.
Step-by-Step Explanation:
We start with two variables, say a and b.
First, we add b to a. This gives us a sum that contains the values of both a and b.
Next, we subtract b (which is still the original value of b) from the sum stored in a. This subtraction leaves us with the original value of a stored in b.
Finally, we subtract the new value of b from the sum stored in a. This gives us the original value of b in a.
Example:
Let’s swap the numbers 12 and 8 using this method.
#include <stdio.h>
int main() {
int a, b;
// Input from the user
printf("Enter two numbers (a and b): ");
scanf("%d %d", &a, &b);
printf("Before swap: a = %d, b = %dn", a, b);
// Swapping using addition and subtraction
a = a + b; // a now becomes 20
b = a - b; // b becomes 12 (original value of a)
a = a - b; // a becomes 8 (original value of b)
printf("After swap: a = %d, b = %dn", a, b);
return 0;
}
Output:
Enter two numbers (a and b): 7 and 10
Before swap: a = 12, b = 8
After swap: a = 8, b = 12
The beauty of this method is in its simplicity.
It’s just three lines of code after the input. There’s no need for a temporary variable, and we get the job done efficiently.
Key Points to Remember:
Avoid overflow: Be cautious with very large numbers, as adding them might cause an overflow.
Perfect for integers: This method works best with integers. Avoid using it with floating-point numbers, as precision issues can arise.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Method 2: Swapping Two Numbers Using Multiplication and Division
If we would like to look into another way of swapping without using a third variable, multiplication and division can help us. It will apply the very idea of addition and subtraction but use multiplication and division instead.
Step-by-Step Explanation:
Start with two variables, a and b.
Multiply a by b and store the result in a. Now, a contains the product of the original values of a and b.
Divide the new a (which is the product) by b to retrieve the original value of a and store it in b.
Finally, divide the new a (still the product) by the new b to retrieve the original value of b and store it in a.
Example:
Let’s swap the numbers 7 and 3 using multiplication and division.
#include <stdio.h>
int main() {
double num1, num2;
// Taking user input
printf("Enter first number: ");
scanf("%lf", &num1);
printf("Enter second number: ");
scanf("%lf", &num2);
// Swapping using multiplication and division
if (num2 != 0 && num1 != 0) { // Ensure neither number is zero
num1 = num1 * num2; // num1 now holds the product of num1 and num2
num2 = num1 / num2; // num2 now holds the original value of num1
num1 = num1 / num2; // num1 now holds the original value of num2
// Display the result
printf("After swapping: n");
printf("First number: %.2lfn", num1);
printf("Second number: %.2lfn", num2);
} else {
printf("Swapping using multiplication and division cannot be performed when one of the numbers is zero.n");
}
return 0;
}
Output:
Enter first number: 7
Enter second number: 3
After swapping:
First number: 3.00
Second number: 7.00
Key Points to Remember:
Division by zero: The method defined above does not work if one of the numbers is zero. Before performing a division, always check that neither number is equal to zero.
Risk of overflow: As in addition and subtraction, we also handle big numbers with caution here since the product may turn out greater than the maximum value that can be stored in an integer.
Method 3: Swapping Two Numbers Using the Bitwise XOR Operator
Are you looking for a more advanced method to swap two numbers without a third variable? Let’s dive into the Bitwise XOR technique.
Why XOR?
The XOR operation is a bitwise function that compares each bit of two numbers.
If the bits are different, XOR gives a 1; if they’re the same, it gives a 0. This characteristic allows us to swap values in a clever way without needing extra memory space.
Step-by-Step Explanation:
Start with two variables, a and b.
Perform a = a ^ b. Now, a holds the XOR of the original a and b.
Perform b = a ^ b. This operation gives the original value of a, and stores it in b.
Perform a = a ^ b. This step retrieves the original value of b, and stores it in a.
Example:
Let’s swap the numbers 15 and 9 using the XOR operator.
#include <stdio.h>
int main() {
int a, b;
// Taking user input
printf("Enter the first number (a): ");
scanf("%d", &a);
printf("Enter the second number (b): ");
scanf("%d", &b);
// Displaying numbers before swapping
printf("nBefore swapping: a = %d, b = %dn", a, b);
// Swapping using XOR operator
a = a ^ b;
b = a ^ b;
a = a ^ b;
// Displaying numbers after swapping
printf("After swapping: a = %d, b = %dn", a, b);
return 0;
}
Key Points to Remember:
This method is efficient and avoids the pitfalls of arithmetic overflow
This method works best with integer data types
Using it with floating-point numbers or pointers can lead to unexpected results.
Important Considerations When Swapping Numbers Without a Temporary Variable
When we swap numbers without a third variable, we must be careful about a few things. These methods are not one-size-fits-all. Let’s break down what to watch out for.
Be Mindful of Data Types
Each method works differently with various data types.
Addition/Subtraction and Multiplication/Division: These methods are great with integers but can cause trouble with floats or doubles due to precision loss.
Bitwise XOR: It’s perfect for integers but not suitable for floating-point numbers or pointers. Stick to what’s safe.
Handle Zeroes with Care
If either of the numbers is zero, the multiplication/division method can lead to a division by zero error, crashing your program.
It’s crucial to check that neither number is zero before using this approach.
Watch Out for Overflow
When dealing with very large numbers, an addition/subtraction or multiplication/division method may be overrun.
This occurs when the result is greater than the maximum value that can be stored in an integer.
To avoid this, try using larger capacity data types like long or long long; even so, it’s better to use it carefully.
Stick to Integers for XOR
The XOR method shines with integers, thanks to its bitwise nature. But it’s not designed for floats, doubles, or pointers.
If you try it with these types, you’ll likely run into problems.
Consider Readability and Maintenance
While these methods are clever, they can also be confusing to someone reading your code later.
However, sometimes it is worthwhile using a temporary variable for clarity when working in a team or writing code which others will maintain.
Common Mistakes to Avoid When Implementing These Methods
Swapping two numbers without a third variable sounds simple, but there are common mistakes we need to avoid.
Ignoring Data Type Limits
Forgetting about the limits of the data types can lead to unexpected results.
Always be aware of the maximum and minimum values that your data type can handle.
Neglecting Zero Checks
Using the multiplication/division method without checking for zero is a rookie mistake.
Always ensure that neither a nor b is zero before proceeding with the swap.
Misusing XOR with Non-Integer Types
Trying to use the XOR method with non-integer types like floats, doubles, or pointers can mess up your program.
Stick to integers, where XOR works flawlessly.
Overlooking Overflow Risks
When working with large numbers, always be cautious of overflow.
It’s easy to miss, but it can lead to incorrect results or crashes.
Sacrificing Code Clarity
While it’s tempting to show off with these techniques, remember that readability matters.
If your code becomes hard to understand, it might be better to use a temporary variable.
Conclusion
Learning how to write a C Program to swap two numbers without using third variable requires a lot more than traditional programming knowledge.
It is a skill that can improve our proficiency in writing optimal code and optimising our programs.
Each of the ways – by addition and subtraction, multiplication and division, or the bitwise XOR method – has its own benefits.
Hereby, recognizing the advantages and drawbacks of these techniques, we may determine which of them is the most suitable one for a particular task.
FAQs
Why is swapping two numbers without using a third variable important?
Swapping without a third variable is a classic programming exercise that challenges us to think creatively.
It’s also useful in low-memory situations where every byte counts.
What happens if one of the numbers is zero when using the multiplication and division method?
If one of the numbers is zero, the multiplication and division method will fail due to division by zero.
This will cause an error, so it’s essential to check for zero before using this method.
Is bitwise XOR the suitable method for all data types?
No, the XOR method can only be applied effectively on integers. It does not work well with floats, doubles, or pointers.
What can I do if my numbers are very large and I am concerned with issues of overflow?
If you’re concerned about overflow, then the XOR method is preferable because it doesn’t use addition or multiplication operations.
On the other hand, consider using broader data types, such as long or long long.
When should I prefer using a temporary variable over these methods?
Use a temporary variable when the clarity of the code is crucial, for example, when working in a team or when writing code over which other people will likely be working.
It makes the code more readable and reduces the incidence of errors to a large extent.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.