In this program, You will learn C Program to Swap two numbers using temporary variables or without temporary variables.
Swapping of two numbers means exchanging values of two variables with each.
For example:
before swapping a=10, b=5
after swapping a=5 and b=10
#include<stdio.h>
int main()
{
int a=10,b=5,temp;
printf("before swapping \n a=%d and b=%d",a,b);
temp=a;
a=b;
b=temp;
printf("\nafter swapping two number\n a=%d and b=%d",a,b);
return 0;
}
before swapping a=10 and b=5 after swapping two number a=5 and b=10
a
in a temporary variable say temp
. temp=a
b
into the first number i.e a
. a=b
temp
into the second number. b=temp
#include<stdio.h>
int main()
{
int a=10,b=5;
printf("before swapping \n a=%d and b=%d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\nafter swapping two number\n a=%d and b=%d",a,b);
return 0;
}
before swapping a=10 and b=5 after swapping two number a=5 and b=10