How to swap two values using a single variable ?
condition: Not to use Array and Pointer ?
Answers were Sorted based on User's Feedback
GOOD MORNING,
swapping itself means that there must be minimum 2
variables ... if there is the way for above , that one is
not called as swapping......
Is This Answer Correct ? | 17 Yes | 2 No |
Answer / ankit anupam
well i think this was wht u were lookin for
#include<stdio.h>
int main()
{
int a, b;
printf("Enter two no");
scanf("%d%d",&a,&b);
printf("a=%d nd b=%d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("a=%d nd b=%d",a,b);
return 0;
}
Is This Answer Correct ? | 16 Yes | 3 No |
Answer / 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 |
Answer / aditya
main(){
int a=10,b=20;
printf("%d%d",a,b);
a^=b,b^=a,a^=b;
printf("%d%d",a,b);
}
Is This Answer Correct ? | 3 Yes | 1 No |
Answer / jyotsna
let take a single variable 'x'
a=3
b=2
hence
x=a;
a=b;
b=x;
swapping is occured now a=2 and b=3
Is This Answer Correct ? | 10 Yes | 12 No |
find the value of y y = 1.5x+3 for x<=2 y = 2x+5 for x>2
can any one tel me wt is the question pattern for NIC exam
What is the real difference between arrays and pointers?
27 Answers Hexaware, Logic Pro, TCS,
Can anyone tell what is stack overflow? what precaution we should take?
What is pragma c?
What is malloc() function?
write function to reverse char array ... without using second array
What is a symbolic constant?
Write a C program to count the number of email on text
how to print this sereis 2 4 3 6 5..........?
void main() { //char ch; unsigned char ch; clrscr(); for(ch =0;ch<= 127; ch++) printf(" %c= %d \t ", ch, ch); } output?
what is a non volatile key word in c language?