Swapping Two Variables in C
Swapping two variables involves exchanging their values, a fundamental concept in programming. This operation is common in various algorithms, such as sorting or shuffling data. This blog will discuss a C program that demonstrates swapping, understand its underlying logic, and explore why it might not always behave as expected.
Introduction to Swapping
Swapping refers to the process of interchanging the values of two variables. For example, if you have two variables a = 5
and b = 10
, after swapping, their values will be a = 10
and b = 5
.
In C programming, swapping can be achieved in different ways:
- Using a temporary variable (the most straightforward approach).
- Without a temporary variable (using arithmetic or bitwise operations).
- Using pointers (to reflect changes in the original variables).
This blog focuses on swapping using a temporary variable in a simple C program and explains why it might not always work as intended.
The C Program
Here is the program to swap two variables using a temporary variable:
Explanation of the Code
- The
main()
function accepts two integer inputs,a
andb
, and prints their initial values before swapping. - The
swap()
function is called to perform the swapping operation - A temporary variable
temp
is introduced to store the value ofx
(copy ofa
). - The value of
y
(copy ofb
) is assigned tox
. - Finally, the value stored in
temp
is assigned back toy
. - The swapped values are printed within the
swap()
function. - In this program, the function
swap()
receives copies ofa
andb
as arguments (x
andy
), not the actual variables themselves. - Changes to
x
andy
inside the function do not affect the originala
andb
inmain()
.
Social Handles