Swapping of two numbers in c with or without using third variable in C

Here we are going to swap two number in c, for this we can use two ways to swap the numbers in c:-

  • swap two number using third variable
  • swap two number without a third variable

So Let’s Not waste the time and code to swap the numbers

Swap two number using third variable

 

#include <stdio.h>
#include<conio.h>
void main()
{
int a,b,c; //declaring variables
clrscr();
a=10; //assigning values
b=20;
printf("These are the values before swapping a=%d and b=%d\n",a,b);
c=a; //now c is have been assigned as 'a' having the value 10
a=b; //now a becomes 20
b=c; //and b becomes 10
printf("These are the values affter swapping a=%d and b=%d\n",a,b);
getch();
}

Let us suppose we have declared the following variables and having values as follows :

int a=10;
int b=20;

Now we want to swap their values so that we’ll get as 20 and b as 10.

For doing this thing we need to create another variable let’s suppose its c. As you are reading this article you must be familiar with assignment of any variable. So, lets try to understand the following operation of assigning values :

c=a;
a=b;
b=c;

So, here we have created another variable called c. Now we are assigning the value to c which is of a. Now c will be holding the value of a that is 10 (c=10 as now).

In the second line we are updating the value of a from 10 to b. So, a will be holding the value of b which is 20. Now a becomes 20. We are now done with half of the work.

In the third line we are again updating the value of b to c. and we already know that c is holding the value if a. So, indirectly b is now holding the value of a.

Woohh..!! That’s all we needed. The values have been swapped.  a is holing the value of b and b is holding the value of a.

Here is the output of the above code :

Output

Swapping numbers without using third variable in C

As you have seen we have swapped the values of two variables using the third variable. Here in this particular section we will do the same thing but in a different way.

#include <stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
a=10;
b=20;
printf("These are the values before swapping a=%d and b=%d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("These are the values affter swapping a=%d and b=%d\n",a,b);
getch();
}

Lets take the same values as above

int a=10;
int b=20;

To do the swapping we just have the three lines of code

a=a+b;
b=a-b;
a=a-b;

Here in the first line we are just updating the values of a from a to a+b. Which than becomes a=30. Now in the second line we are again updating the value of b as a-b. Which results the same value as of initial value of a. Now b has a value as 10.

As of now a have the value as 30 and b have the value 10. But we want a as 20. So, simply we are subtracting b from a. Hence a becomes 20 which is the previous value of b.

check out related example : – c program to check leap year.

Leave a Reply

avatar
  Subscribe  
Notify of