Swapping Two Variables in C

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 and b, 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 of x (copy of a).
  • The value of y (copy of b) is assigned to x.
  • Finally, the value stored in temp is assigned back to y.
  • The swapped values are printed within the swap() function.
  • In this program, the function swap() receives copies of a and b as arguments (x and y), not the actual variables themselves.
  • Changes to x and y inside the function do not affect the original a and b in main().

Output



Conclusion

Swapping is a fundamental concept in programming, and this blog covered its implementation using a temporary variable. We explored how call-by-value in C limits changes to original variables and how pointers can overcome this limitation. Mastering these basics strengthens your understanding of C programming and prepares you for more advanced techniques.