In the world of programming, the need of swapping variables is a common occurrence. Whether you’re working on a simple task or a more complex problem, knowing how to exchange the values of two variables can be extremely useful. In this blog post, we will explore a basic C program that demonstrates how to swap two variables using three different methods. This fundamental concept is not only essential for beginners but also serves as a building block for more advanced programming tasks.
Table of Contents
ToggleMethod 1: Understanding Swapping Variables Using a Temporary Third Variable:
Before we dive into the code, let’s understand the concept of variable swapping. Swapping variables means interchanging their values. In this case, we will use a temporary variable to store one variable’s value temporarily while we exchange the values of the two variables.
The C Code:
Here’s the C code that accomplishes variable swapping:
#include <stdio.h>
int main() {
int p, q, c;
printf("Enter values of p and q: ");
scanf("%d %d", &p, &q);
printf("Before swapping, p = %d and q = %d\n", p, q);
c = p;
p = q;
q = c;
printf("Values after swapping, p = %d and q = %d\n", p, q);
return 0;
}
Explanation of the Code:
- We start by including the standard I/O library,
<stdio.h>
which provides functions for input and output operations. - Inside the
main
function, we declare three integer variables: p,q
, andc
. p andq
are the variables we want to swap, andc
is a temporary variable used for swapping. - We prompt the user to input values for p and q using
scanf
. Thescanf
function reads two integer values separated by a space and stores them in p andqb
. - We print the values of p and
q
before swapping usingprintf
. - To swap p and
q
, we use the temporary variablec
. First, we store the value of p inc
, effectively preserving it. Then, we assign the value of q to p and, finally, assign the value stored inc
(the original value of p) to q. - We print the values of p and q after swapping to demonstrate that the swap has occurred.
Output :
Enter values of p and q: 12
5
Before swapping p = 12 and q = 5
Values after swapping p = 5 and q = 12
While the traditional method uses a temporary variable to store one of the values temporarily, there’s a clever and efficient way to do it using bitwise XOR operations. We’ll explore a C program that demonstrates how to swap two variables without using an additional variable. This bitwise approach is not only fascinating but also serves as a valuable addition to your programming toolkit.
Method 2: Understanding Bitwise XOR Swapping:
Before we dive into the code, let’s understand how the bitwise XOR operation works for swapping variables. XOR (exclusive OR) returns 1 if the corresponding bits of two numbers are different and 0 if they are the same. Here’s how it works:
- If we XOR a number with itself, it sets all bits to 0.
- If we XOR a number with 0, it remains unchanged.
- XOR is commutative, meaning p
^ q
is the same asq ^ p
.
The C Code:
Here’s the C code that swaps two variables using bitwise XOR:
#include <stdio.h> int main() { int p, q; printf("Enter values of p and q: "); scanf("%d %d", &p, &q); printf("Values before swapping: p = %d and q = %d\n", p , q); p = p ^ q; q = p ^ q; p = p ^ q; printf("After swapping: p = %d and q = %d\n", p, q); return 0; }
Explanation of the Code:
- We include the standard I/O library,
<stdio.h>
, for input and output operations. - Inside the
main
function, we declare two integer variables, p andq
, which we want to swap. - We prompt the user to input values for p and
q
usingscanf
. - We print the values of p and
q
before swapping to show their initial values. - The actual swapping happens using bitwise XOR operations. We use
p = p ^ q
to XORp
with q and store the result inp
. This effectively combines the values of p andq
inp
. Then, we useq = p ^ q
to XOR the new value of p withq
and store it in q. Finally, we usep = p ^
q to XOR the new value of q with p and store it in p. This sequence of XOR operations swaps the values of p andq
without using an additional variable. - We print the values of p and
Output:
Enter values of p and q: 5
3
Values before swapping p = 5 and q = 3
After swapping p = 3 and q = 5
Clearer Explanation of Output:
- Initialize p and
q
:- p = 5 (binary: 0101)
- q = 3 (binary: 0011)
- First XOR operation:
p = p ^ q
:- p becomes
p ^ q
, which is equivalent to0101 ^ 0011
. - The result is
0110
(6 in decimal), and p now holds the value 6.
- p becomes
- Second XOR operation:
q = p ^ q
:- Now that
p
is 6 and q is 3, we performp ^
q, which is0110 ^ 0011
. - The result is
0101
(5 in decimal), and q is updated to 5.
- Now that
- Third XOR operation:
p = p ^ q
:- Finally, we perform
p ^
q, which is0110 ^ 0101
. - The result is
0011
(3 in decimal), and p is updated to 3.
- Finally, we perform
We’ll explore a C program that demonstrates how to swap two variables using addition and subtraction. This method is not only elegant but also provides a valuable learning experience for programmers of all levels.
Method 3: Understanding Arithmetic Swapping:
Before diving into the code, let’s grasp the concept of swapping variables using addition and subtraction. The idea is to perform mathematical operations that allow us to exchange the values of p and q without using any additional memory.
The C Code:
Here’s the C code that swaps two variables using arithmetic operations:
#include <stdio.h>
int main() {
int p, q;
printf("Enter values of p and q: ");
scanf("%d %d", &p, &q);
printf("Before swapping: p = %d and q = %d\n", p, q);
p = p + q;
q = p - q;
p = p - q;
printf("After swapping: p = %d and q = %d\n", p, q);
return 0;
}
Explanation of the Code:
- We include the standard I/O library,
<stdio.h>
, to handle input and output operations. - Inside the
main
function, we declare two integer variables, p and q, which we want to swap. - We prompt the user to input values for p and q using
scanf
. - To visualize the initial values, we print the values of p and q before swapping.
- The actual swapping is achieved through arithmetic operations. Here’s how it works:
p = p + q
adds the values of p andq
and stores the result in p, effectively combining both values.q = p - q
subtracts the new value ofq
fromp
, which results in the original value of p. This step assigns the original value of p toq
.- Finally,
p = p -
q subtracts the value of the newly swapped q from p, resulting in the original value ofb
being assigned to p.
- After swapping, we print the values of
p
and q to confirm that the exchange has taken place successfully.
Output:
Enter values of p and q: 50
90
Values before swapping p = 50 and q = 90
After swapping p = 90 and q = 50
Clearer Explanation of Output:
- Initialize p and q:
- p = 90
- q = 50
- First step:
p = p +
q:- p becomes
90 +
50, which is 140. - So, p is now 140.
- p becomes
- Second step:
q = p - q
:- q becomes
140 -
50, which is 90. - So, q is now 90.
- q becomes
- Third step:
p = p - q
:- p becomes
140 -
90, which is 50. - Now, p holds the original value of q, which is 50.
- p becomes
Conclusion
Swapping variables, whether using a temporary variable, bitwise XOR, or arithmetic operations, is a fundamental programming concept that serves various purposes. Here’s a conclusion summarizing the key points of swapping variables:
- Traditional Swapping with a Temporary Variable:
- This method involves using a temporary variable to hold one of the values temporarily while you exchange the values of two variables.
- It is simple, easy to understand, and commonly used in programming.
- Suitable for most situations and doesn’t rely on specific properties of the data types involved.
- Bitwise XOR Swapping:
- XOR-based swapping is a clever technique that leverages the properties of the XOR operation.
- It efficiently exchanges the values of two variables without using a temporary variable.
- XOR swapping is memory-efficient and can be particularly useful in situations where memory allocation is constrained.
- Arithmetic Swapping:
- Arithmetic-based swapping relies on addition and subtraction operations.
- It is another memory-efficient method to swap variables without a temporary variable.
- Simple and straightforward, it can be a valuable tool when memory efficiency is a concern.
In conclusion, swapping variables is a fundamental skill in programming, and the method you choose depends on your specific needs and constraints. Traditional swapping with a temporary variable is often the easiest to understand and implement, while bitwise XOR and arithmetic swapping offer memory-efficient alternatives. Understanding these different methods equips you with valuable tools for solving a wide range of programming challenges efficiently and elegantly.
Read this also: Clarity to 2 Concepts- Post-Decrement and Pre-Decrement in C (codershot.com)
Here’s the YouTube video for more convenience