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
Explain what are its uses in c programming?
Write a progarm to find the length of string using switch case?
Is it better to use a macro or a function?
What are pragmas and what are they good for?
What is a macro in c preprocessor?
What is malloc return c?
What is advantage of pointer in c?
How to find a missed value, if you want to store 100 values in a 99 sized array?
Tell us two differences between new () and malloc ()?
What are preprocessor directives in c?
what do you mean by enumeration constant?
What happens if header file is included twice?
When is a void pointer used?
What is the difference between strcpy() and memcpy() function in c programming?
Here is a neat trick for checking whether two strings are equal