C Program to swap two number without third variable

Ans: 

In this tutorial you will learn how to Swap two numbers without using third variable in C programming language.

This swapping of two numbers in C program is very frequently asked question in interview and also it is very important program.

Before directly moving on writing the program lets understand what is our aim to achieve in this program.

Basically Swapping of number means 

Suppose we have two variable ‘a’ and ‘b’, we have assigned value 2 and 4 in it respectively. In swapping operation we will exchange the value and assign value of a which is 2 in b and the value of b which is 4 in variable a.

How our program will behave?

As we already seen above that what we have to achieve in the program.

In the swapping program without using third variable we will assign two different value to two different variables.

For example: a=2 and b=4

Now after execution of the program our output should like 

a=4 and b = 2

C Program to swap two number without using third variable

#include<stdio.h>
#include<conio.h>
void main() {
  int a, b;
  printf("enter the value of a: ");
  scanf("%d", & a);
  printf("enter the value of b: ");
  scanf("%d", & b);
  a = a - b;
  b = a + b;
  a = b - a;
  printf("After swapping \n");
  printf("value of a is : %d \n", a);
  printf("value of b is : %d ", b);
  getch();
}

Output 1:

enter the value of a: 32
enter the value of b: 12
After swapping 
value of a is : 12 
value of b is : 32 

Output 2:

enter the value of a: 66
enter the value of b: 11
After swapping 
value of a is : 11 
value of b is : 66 

Explanation of the above program

  • Swapping program is really very important program which is asked by interviewers.
  • In the above program there are two variables ‘a’ and ‘b’ in which we assign the inputs.
  • Lets see the logic, in variable ‘a’ we are assigning value after the subtraction of value of ‘a’ variable with value of ‘b’ variable.
  • Now in variable ‘b’ we are assigning the value after the addition of new value of variable ‘a’ with value of ‘b’ variable.
  • By doing this we get sum of original value of variable ‘a’ and ‘b’.
  • Now ‘b’ has sum of original value and ‘a’ has value which was on ‘b’ previously.
  • To calculate the value of variable ‘a’ we will subtract value of variable ‘a’ from ‘b’ and will assign it to variable ‘a’.
  • At last you will find that value of variable ‘a’ has now value that was in ‘b’. And ‘b’ has that was in ‘a’.

I hope you have cleared the swapping program concept in C.

Leave a Comment