Swapping of Two Numbers in C - With and Without Third Variable

In this example, You learn about swapping of two numbers in c. I shared swap two numbers using third variable and swap two numbers without using third variable.

Before you start I think you are familiar with the term swap and if not follow - 

Swap

In simple words, The term Swap means exchange or interchange. In normal exchange of anything like positions, seats in trains, etc. between two parties.
Now I can relate this to computer science. In computer programming, we can swap the positions of two variables, swap the values of variables.

Swapping of Two Numbers in C

Swap Two Numbers Using Third Variable

Program


#include<stdio.h>
int main()
{
    int a,b,temp;
     printf("\n Enter Two Numbers:-");
     scanf("%d%d",&a,&b);
     printf("\n Before Swap a=%d \t and b=%d \n ",a,b);
       temp=a;
       a=b;
       b=temp;
     printf("\n After Swap a=%d \t and b=%d \n ",a,b); 
     return 0;
}
For example, if a user enters 45 and 12 then the output will be:

Enter Two Numbers:-
45
12
Before Swap a=45 and b=12
After Swap a=12 and b=45
 

Swap Two Numbers Without Using Third Variable

Program


#include<stdio.h>
int main()
{
   int a,b;
    printf("\n Enter Two Numbers:-");
    scanf("%d%d",&a,&b);
    printf("\n Before Swap a=%d \t and b=%d \n ",a,b);
      a=a+b;
      b=a-b;
      a=a-b;
    printf("\n After Swap a=%d \t and b=%d \n ",a,b); 
   return 0;
} 
For example, if the user enters 46 and 35 then the output will be:

Enter Two Numbers:-
46
35
Before Swap a=46 and b=35
After Swap a=35 and b=46
 

Conclusion 

Now I think you understand swapping and don't forget if you are not confident then revisit once again. In the upcoming tutorial, I will share the swapping of two numbers in python and Java. 

If you have any doubts in the above article feel free to ask in the comment box below.

Happy Coding 😊

If you have any doubts, Please let me know

Previous Post Next Post

Contact Form