Swapping
is a interchanging of variable. Consider variable a and b if a=23,b=47. After swapping a=47,b=23
1)
Swapping of two numbers in c using third
variable
#include<stdio.h>
main()
{
int a=23,b=47,temp;
printf("Before Swap. a: %d, b:
%d\n", a, b);
temp=a;
a=b;
b=temp;
printf("After
Swap. a: %d, b: %d\n", a,
b);
return 0;
}
output
Before
Swap. a: 23, b: 47
After
Swap. a: 47, b: 23
2)
Swapping of two numbers without using third
variable
#include<stdio.h>
main()
{
int a=23,b=47;
printf("Before Swap. a: %d, b:
%d\n", a, b);
a=a+b;
b=a-b;
a=a-b;
printf("After
Swap. a: %d, b: %d\n", a,
b);
return 0;
}
Output
Before
Swap. a: 23, b: 47
After Swap.
a: 47, b: 23
3)
Swapping of two variables using bitwise
operation
#include<stdio.h>
main()
{
int a = 23, b = 47;
printf("Before Swap. a: %d, b:
%d\n", a, b);
a
^= b;
b
^= a;
a
^= b;
printf("After Swap. a: %d, b: %d\n", a, b);
return 0;
}
output
Before
Swap. a: 23, b: 47
After
Swap. a: 47, b: 23
No comments:
Post a Comment
Comment Here..