Thursday, April 12, 2012

Exchanging the value of Variables

In this post we shall look at the various ways of interchanging the values of variables. We shall not be looking into methods involving loops, but only simple expression based methods.

Essentially, any binary operation which has an inverse can be used as a basis for the exchange. Thus, we shall use the assignment operator, addition, subtraction, multiplication and division. The last two will require the divisor to be non zero.


Here is the program which does this exchange.

Exchange.c

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a=15,b=10,t;
clrscr();
printf("Original values a=%f,b=%f",a,b);
printf("\nSwap using a temporary variable\n");
t=a;a=b;b=t;
printf("Swapped values a=%f,b=%f",a,b);
printf("\nSwap using a substraction\n");
a=a-b;b=a+b;a=b-a;
printf("Swapped values a=%f,b=%f",a,b);
printf("\nSwap using a addition\n");
a=a+b;b=a-b;a=a-b;
printf("Swapped values a=%f,b=%f",a,b);
printf("\nSwap using a multiplication\n");
a=a*b;b=a/b;a=a/b;
printf("Swapped values a=%f,b=%f",a,b);
printf("\nSwap using a division\n");
a=a/b;b=a*b;a=b/a;
printf("Swapped values a=%f,b=%f",a,b);
getch();
}
This is the output of the program

Original values a=15.000000,b=10.000000
Swap using a temporary variable
Swapped values a=10.000000,b=15.000000
Swap using a substraction
Swapped values a=15.000000,b=10.000000
Swap using a addition
Swapped values a=10.000000,b=15.000000
Swap using a multiplication
Swapped values a=15.000000,b=10.000000
Swap using a division
Swapped values a=10.000000,b=15.000000


Rotation of values
Rotation of values a<--b, b<-- c, c<-- a

This is accomplished through the following program code.

#include<stdio.h>
#include<conio.h>
void main()
{
int a=1,b=2,c=3,t;
clrscr();
printf("Original values a=%d,b=%d,c=%d\n",a,b,c);
t=a;
a=b;
b=c;
c=t;
printf("Rotated values a=%d,b=%d,c=%d\n",a,b,c);
getch();
}

Here is the output of this program

Original values a=1,b=2,c=3
Rotated values a=2,b=3,c=1


Exchanging two elements via a temporary variable is a special case of the general rotation problem. As an interesting aside we can see that for n elements to be rotated, n rotations would give back the original set.

No comments:

Post a Comment