Sunday, 14 October 2012

how to swap two numbers without using temporary variable.?

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();

}


output:

 Before swapping a:15, b=20

No comments:

Post a Comment