Its very easy to swap two numbers using temporary variable. but how to swap without using temporary variable.?
This is one of the question in most of the coding competitions and technical interviews.
So i think it might be helpful for many students or coding geeks..
It can be done using arithmetic operators
The code for the same is given below:
#include
void main()
{
//swapping without using temporary variable
//but usng arithmetic operators
int a=15,b=20;
clrscr();
printf("\nBefore swapping a:%d, b=%d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\nAfter swapping a:%d, b=%d",a,b);
getch();
}
Before swapping a:15, b=20
After swapping a:20, b=15
void main()
{
//swapping without using temporary variable
//but usng arithmetic operators
int a=15,b=20;
clrscr();
printf("\nBefore swapping a:%d, b=%d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\nAfter swapping a:%d, b=%d",a,b);
getch();
}
No comments:
Post a Comment