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 |
How to write in a function declaration and in function call in which the function has 'n' number of varible or arguments?
Devise a program that inputs a 3 digit number n and finds out whether the number is prime or not. Find out its factors.
1. What will be the output of the following programs. a) #include <stdio.h> Main() { Int x=4; While(x==1) { X=x-1; Printf(ā%dā,x); --x; } }
What is the value of c?
what is the use of bitfields & where do we use them?
What is a pointer value and address in c?
i = 25;switch (i) {case 25: printf("The value is 25 ");case 30: printf("The value is 30 "); When the above statements are executed the output will be : a) The value is 25 b) The value is 30 c) The value is 25 The value is 30 d) none
What is the 'named constructor idiom'?
in linking some of os executables are linking name some of them
please explain clearly about execution of c program in detail,in which stage are the printf sacnf getting into exeecutable code
When should a type cast not be used?
What is substring in c?