void main() { int a,b; clrscr(); printf("\n\n\t\tenter any two nos..."); scanf("%d%d",&a,&b); a=a+b; b=a-b; a=a-b; printf("\n\n\t\tvalue of a=",a); printf("\n\n\t\tvalue of b=",b); getch(); }
To swap two variables using a third variable in a flowchart, start with the initial values of the two variables, say A and B. Use a third variable, C, to temporarily hold the value of A (C = A). Next, assign the value of B to A (A = B), and finally, assign the value of C back to B (B = C). This sequence effectively swaps the values of A and B.
A = A xor B B = A xor B A = A xor B in C... A^=B; B^=A; A^=B;
a ^= b; b ^= a; a ^= b;
There are three primary algorithms to exchange the values of two variables. Exchange with Temporary Variable temp = a; a = b; b = temp; Exchange Without Temporary Variable Using Exclusive Or a = a ^ b; b = b ^ a; a = a ^ b; Exchange Without Temporary Variable Using Arithmetic a = a + b; b = b - a; a = a - b;
Use list assignment i.e. for two variables $a, $b: ($a,$b) = ($b,$a)
To swap two variables without using a third variable, use exclusive or manipulation... a ^= b; b ^= a; a ^= b;
By using a third temporary variable. $tmp = $a; $a = $b; $b = $tmp;
Nothing. Never do that.
To swap two variables using a third variable in a flowchart, start with the initial values of the two variables, say A and B. Use a third variable, C, to temporarily hold the value of A (C = A). Next, assign the value of B to A (A = B), and finally, assign the value of C back to B (B = C). This sequence effectively swaps the values of A and B.
A = A xor B B = A xor B A = A xor B in C... A^=B; B^=A; A^=B;
Controlling variables is when you make sure that only one variable is being tested at a time and that there are not other variables that will make your results unclear. Using a control is when you do a trial without the variable to see what the normal results are.
a ^= b; b ^= a; a ^= b;
There are three primary algorithms to exchange the values of two variables. Exchange with Temporary Variable temp = a; a = b; b = temp; Exchange Without Temporary Variable Using Exclusive Or a = a ^ b; b = b ^ a; a = a ^ b; Exchange Without Temporary Variable Using Arithmetic a = a + b; b = b - a; a = a - b;
a=a^b; b=a^b; a=a^b;
Use list assignment i.e. for two variables $a, $b: ($a,$b) = ($b,$a)
The required c program is given below /*Swapping(interchange) the two entered numbers*/ #include<stdio.h> main() { /*Without using third variable*/ int a,b,t; printf("Enter a:"); scanf("%d",&a); printf("Enter b:"); scanf("%d",&b); a=a+b; b=a-b; a=a-b; printf("\n After swapping without using third variable"); printf("\na=%d\nb=%d",a,b); }
There are two ways in which you can swap without a third variable. 1. Using xor operation swap( int *a, int *b) { *a = *a ^ *b; *b = *a ^ *b; *a = *a ^ *b; } 2. Using addition and subtraction swap( int *a, int *b) { *a = *a + *b; *b = *a - *b; *a = *a - *b; } }