C Program to swap two numbers without using third variable

C Program to swap two numbers without using third variable


C Program to swap two without using third variable : Swapping of variables means mutually exchanging the values of the variables. Swapping data is a very important component of numerous . For example, many of the , especially comparison sorts, utilize swaps to change the positions of data. We can swap variables using two methods, first by using temporary third variable and second without using third variable. Below are both ways of doing that :

Swapping without using third Variable:

* Only valid for whole number(number greater than 0).


Swapping using third temporary variable:

 temp = x
 x = y
 y = temp

Today we will learn how to write a to swap two numbers without using third variable. Below is the simple C program which accepts two numbers as input and then swaps their values.

C program to swap two numbers without using third variable:

void main()
int a,b;
printf("nEnter value for num1 & num2 : ");
scanf("%d %d",&a,&b);
printf("nAfter swapping value of a : %d",a);
printf("nAfter swapping value of b : %d",b);

That’s all friends. Now compile the code and execute it. If you have any queries or doubts ask us in form of comments.




  1. Hi ! I am a regular visitor of your website. It’s very good source for the beginners like me. I just wanted to ask you that, for every program you post, please give how the logic works, Thanks.

  2. If you want to swap to values, best way is to use third variable. The way described above isn’t correct, you just need to take values with different sign to fail the swap (e.g a = 2 b = -5). And even more, swapping float numbers in such a manner may result in precision lose.

  3. void main()
    int a = 10, b = 8;
    printf(” before swapping a = 10 b = 8 \n”);

    /*a = a + b;
    b = a-b;
    a = a – b;*/ // one method for swapping two numbers without using temp

    a = a * b; // another method for swapping two numeber without using temp
    b = a / b;
    a = a / b ;
    printf(” after swapping a = %d b = %d” ,a,b);