Home > Programming > program to swap two numbers with out using temporary variable with in one line

program to swap two numbers with out using temporary variable with in one line


#include <stdio.h>
#include <conio.h>
int main(void)
{
int a , b;
printf(“Enter two integers: “);
scanf(“%d%d”,&a,&b);
printf(“Before swapping: a=%d,b=%d\n”,a,b);
a=(a+b)-(b=a); //This is just one line
printf(“After swapping: a=%d,b=%d”,a,b);
getch();
return 0;
}
compiled on :gcc logic :simple and tricky
If you have any doubts please add a comment
Advertisements
  1. kiran reddy
    June 14, 2010 at 12:15 pm

    cool prgm man..

  2. August 8, 2010 at 5:25 pm

    excellent.. post some more logics

    • August 8, 2010 at 5:44 pm

      ok.. I do post. Thank you for your compliments

  3. November 26, 2010 at 5:20 am

    This doesn’t work in Visual Studio 2008.

    In the line (a+b)-(b=a), you are relying on (a+b) to complete before (b=a). This is not necessarily true.

    This is because (a+b) and (b=a) has the same precedence. In this case, VS2008 chooses to perform (b=a) first.

    Here’s the generated assembly from a Debug build.

    a=(a+b)-(b=a);
    mov eax,dword ptr [a]
    mov dword ptr [b],eax
    mov ecx,dword ptr [a]
    mov dword ptr [a],ecx

    … Alan

    • November 26, 2010 at 12:10 pm

      Ya you are correct… I wrote that program in GCC compiler. It may not work in VS 2008. I think this may work Once try this way….
      #include
      int main(void){
      int a=20;
      int b=10;
      printf(“a = %d, b = %d\n”,a,b);
      a=(a+b)-(b=(a+b)-b); // Here is the simple logic
      printf(“a = %d, b = %d\n “,a,b);
      return 0;
      }

  4. divakar
    February 18, 2012 at 1:05 pm

    very very simple logic thank u vasanth.

  5. shubham pandey
    August 18, 2012 at 7:44 pm

    sir please put some more programs with good logic.

  6. March 19, 2014 at 6:48 pm

    very nice

  7. July 20, 2014 at 10:28 am

    I’ve been exploring for a bit for any high quality articles or
    blog posts on this sort of house . Exploring in Yahoo I eventually stumbled upon this
    web site. Studying this info So i am happy to express that I’ve a very excellent uncanny feeling I found out exactly what
    I needed. I most certainly will make sure to
    don?t fail to remember this site and provides
    it a glance regularly.

  1. October 17, 2010 at 7:53 am
  2. August 31, 2011 at 9:32 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: