C program to swap to two numbers without using third variable
C program for how to swap two numbers without an extra variable.
by Krishna viswambharan
Posted on 10 Aug 2017 Category: C
Swap to numbers without using a third variable
Swapping two numbers without using a third variable can be done with arithmetic operators and logic operators. Here we are using arithmetic operation method.
The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.
printf(“Enter the first number :”);
printf(“Enter the second number :”);
printf(“Before swap a=%d b=%d”,a,b);
a=a+b; // a now becomes the sum of a and b
b=a-b; //b stores the value of a
a=a-b; //a stores the value of b
printf(“\nAfter swap a=%d b=%d”,a,b);