Learn C with example
Swap two number using two variables
In this example we are going two swap two
numbers using two variables.
Here first insert two values from keyboard
then add these two values and store values it into one variable. Then second
variable value is stored value -second value and first variable value is stored
value- second variable value.
This is like
a=a+b;
b=a-b=a+b-b=a;
a=a-b=a+b-a=b;
So value of variables are sapped.
/* swap two number using two variables */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter the two numbers\t");
scanf("%d%d",&a,&b);
a=a+b;
b=a-b;
a=a-b;
printf("\n Swapped numbers a=%d b=%d",a,b);
getch();
}
|
Output Of Example
Enter the two numbers 12
13
Swaped numbers a=13 b=12 |