swapping two numbers in C
In this post, we are going to learn how to swap two numbers using a “C” Program. We have many ways to swap the numbers and we are discussing few of them in this post.
In simple words, swapping is nothing but exchanging the variable values. This is mainly useful in Data Structures, for example in sorting algorithms one must compare the given elements and if required we need to swap the numbers. In the next sections, we are going to explain the sorting algorithms, hence i decided to write one post on swapping.
Consider an example,
We have two variables a=10, b=20.
The values of ‘a’ and ‘b’ before swapping (exchanging) are 10 and 20.
The values of ‘a’ and ‘b’ after swapping (exchanging) would be 20 and 10 respectively.
The general method is using a temporary variable.
a=10
b=20
Take a temporary variable and store the value of ‘a’ in to ‘temp’ variable.
temp = a; now ‘temp’ holds the value 10.
Now store the value of ‘b’ in to ‘a’.
a=b; now ‘a’ holds the value 20.
Finally store the value of ‘temp’ to ‘b’.
b=temp; now ‘b’ holds the value 10.
That’s it. You almost done…
The pseudo code is shown below.
The following shows a ‘C’ Program to implement the above pseudo code.
Output:
Enter two numbers
10
20
Before Swapping
a = 20
b = 0
After Swapping
a = 0
b= 20
In the above program, we used a temporary variable. we can also do this task, without using a temporary variable using a simple addition and subtraction logic.
Let’s take again take a= 10, b=20
Step 1: a = a+b
Now ‘a’ holds the value 30. (a=30).
Step 2: b=a-b
Now ‘b’ holds the value 10. (b=10)
Step 3: a=a-b;
Now ‘a’ holds the value 20 (a=20)
The following program shows the swapping of two numbers without using a temporary variable.
Output:
Enter two numbers
10
20
Before Swapping
a = 10
b = 20
After Swapping
a = 20
b = 10
The following program is an example of swapping of two numbers using bit wise XOR without using a temporary variable.
Output:
Enter two numbers
10
20
After Swapping
a = 20
b = 10
The following program is an example of ‘C’ Program to swap two numbers using pointers.
Output:
Enter the value of a and b
10
20
Before Swapping
a = 10
b = 20
After Swapping
a = 20
b= 10