ALGORITHM FOR
EXCHANGING TWO VALUES
EXCHANGING THE VALUES OF TWO VARIABLES




Problem statement
To exchange the values of the variables assigned to
them.
Algorithm development
The problem of interchanging the data associated
with two variables involves a very fundamental
mechanism that occurs in many sorting and data
manipulation algorithm.
Ex:
a
b
4
5
Here a has 4 and b has 5. our aim is to replace the
variable of a with 4 and b with 5.
So the target solution may look as
a
5

b
4

Here we can make use of the assignment operator
a = b; b = a;
where the b value is assigned to a. the value has been
changed, and the changed a value has been assigned to b.
a = 5,

b=5
So we make use of the temporary variable.
t = a;
a = b;
b = t;
Now,
t = 4, a = 5, b = 4
Our target solution has been achieved.
Algorithm Description:
1. Save the original value of a in t.
2. Assign to a the original value of b.
3. Assign to b the original value of a that is stored
in t.
Program Implementation
# include <iostream.h>
#include <conio.h>
main ()
{
int a = 4, b = 5, t;
cout<<“The original value of a=“<<a<<“b=“<<b;
t = a;
a = b;
b = t;
cout<<“After exchanging a=“<<a<<“b=“<<b;
}
APPLICATION


This kind of swapping technique is applicable
for all kinds of sorting algorithm.

Problem Solving Aspect of Swapping Two Integers using a Temporary Variable

  • 1.
  • 2.
    EXCHANGING THE VALUESOF TWO VARIABLES   Problem statement To exchange the values of the variables assigned to them. Algorithm development The problem of interchanging the data associated with two variables involves a very fundamental mechanism that occurs in many sorting and data manipulation algorithm. Ex: a b 4 5 Here a has 4 and b has 5. our aim is to replace the variable of a with 4 and b with 5.
  • 3.
    So the targetsolution may look as a 5 b 4 Here we can make use of the assignment operator a = b; b = a; where the b value is assigned to a. the value has been changed, and the changed a value has been assigned to b. a = 5, b=5
  • 4.
    So we makeuse of the temporary variable. t = a; a = b; b = t; Now, t = 4, a = 5, b = 4 Our target solution has been achieved.
  • 5.
    Algorithm Description: 1. Savethe original value of a in t. 2. Assign to a the original value of b. 3. Assign to b the original value of a that is stored in t.
  • 6.
    Program Implementation # include<iostream.h> #include <conio.h> main () { int a = 4, b = 5, t; cout<<“The original value of a=“<<a<<“b=“<<b; t = a; a = b; b = t; cout<<“After exchanging a=“<<a<<“b=“<<b; }
  • 7.
    APPLICATION  This kind ofswapping technique is applicable for all kinds of sorting algorithm.