Write a program in C to swap two numbers without using third variable

Again a common question asked in IT job interviews and in assignments given to the student to write a program in c to swap two numbers without using the third variable. Here, in the solution, we will take two numbers from the user and store them in variable a and b. Then, we will perform the arithmetic operations on the values of the variables to swap the numbers stored in them.

For Example: Let the values given by user are a=10 and b=20.


a=a+b;// It will give a=30.(10+20)

b=a-b:// it will give b=10;(30-20)

c=a-b:// it will give a=20;(30-10)

Lets see the solution with source code:

void main()
    int a, b;
    printf("Enter the two numbers to swap \n ");
    scanf("%d%d", &a, &b);
    printf("Before Swapping\n a=%d\n b=%d\n", a,b);
    //Logic of Swapping of numbers by using third variable
    a = a+b;
    b = a-b;
    a = a-b;
    printf("After Swapping \n a=%d\n b=%d"\n, a,b);