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
How to find a missed value, if you want to store 100 values in a 99 sized array?
What are lookup tables in c?
Do pointers take up memory?
FILE PROGRAMMING
What is difference between structure and union in c?
How many types of sorting are there in c?
What is a floating point in c?
What are dangling pointers in c?
What is the difference between array and linked list in c?
Define the scope of static variables.
What is a #include preprocessor?
When is a null pointer used?
Explain what are bus errors, memory faults, and core dumps?
write a program to create a sparse matrix using dynamic memory allocation.
What is a dynamic array in c?