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
Views: 631
Edited on 10 Aug 2017
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.
#include <stdio.h>
#include <conio.h>
void main()
{
int a,b;
printf(“Enter the first number :”);
scanf(“%d”,&a);
printf(“Enter the second number :”);
scanf(“%d”,&b);
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);
getch();
}