How to swap two values using a single variable ?

condition: Not to use Array and Pointer ?

Answer Posted / jp

The trick is to use register variables. I have written a sample code in C. There might be some cosmetic works for indention, plz don't bother ;)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#include <dos.h>
#include <stdio.h>
union REGS ax_regs;

/*
Title : Using Registers To Swap Values

Description : Declaring a single variable and using it to swap two values

Author : Jayapriyan VITTOBANE
Turbo C++ V 3.0
*/

void main()
{
clrscr();
ax_regs.h.ah=2;
ax_regs.h.al=3;
printf("\n\n\n\n\n\t\t\tBefore Swapping");
printf("\n\n\n\t\tFirst Value:%5d",ax_regs.h.ah);
printf("\n\n\n\t\tSecond Value:%5d",ax_regs.h.al);
ax_regs.h.ah=ax_regs.h.ah^ax_regs.h.al;
ax_regs.h.al=ax_regs.h.ah^ax_regs.h.al;
ax_regs.h.ah=ax_regs.h.ah^ax_regs.h.al;
printf("\n\n\n\n\n\n\n\n\n\n\t\t\tAfter Swapping");
printf("\n\n\n\t\tFirst Value:%5d",ax_regs.h.ah);
printf("\n\n\n\t\tSecond Value:%5d",ax_regs.h.al);
getch();
}

Is This Answer Correct ?    5 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain what are its uses in c programming?

598


Write a progarm to find the length of string using switch case?

1612


Is it better to use a macro or a function?

658


What are pragmas and what are they good for?

578


What is a macro in c preprocessor?

632






What is malloc return c?

601


What is advantage of pointer in c?

696


How to find a missed value, if you want to store 100 values in a 99 sized array?

820


Tell us two differences between new () and malloc ()?

616


What are preprocessor directives in c?

638


what do you mean by enumeration constant?

599


What happens if header file is included twice?

655


When is a void pointer used?

678


What is the difference between strcpy() and memcpy() function in c programming?

628


Here is a neat trick for checking whether two strings are equal

566