problem solving aspect of swapping two integers using a temporary variable

7
ALGORITHM FOR EXCHANGING TWO VALUES

Upload: saravana-priya

Post on 29-Jun-2015

72 views

Category:

Education


0 download

DESCRIPTION

Problem Solving Techniques

TRANSCRIPT

Page 1: Problem Solving Aspect of Swapping Two Integers using a Temporary Variable

ALGORITHM FOR EXCHANGING TWO VALUES

Page 2: Problem Solving Aspect of Swapping Two Integers using a Temporary Variable

EXCHANGING THE VALUES OF TWO VARIABLES Problem statement

To exchange the values of the variables assigned to them.

Algorithm developmentThe 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.

Page 3: Problem Solving Aspect of Swapping Two Integers using a Temporary Variable

So the target solution may look as

a b 5 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

Page 4: Problem Solving Aspect of Swapping Two Integers using a Temporary Variable

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.

Page 5: Problem Solving Aspect of Swapping Two Integers using a Temporary Variable

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.

Page 6: Problem Solving Aspect of Swapping Two Integers using a Temporary Variable

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;}

Page 7: Problem Solving Aspect of Swapping Two Integers using a Temporary Variable

APPLICATION

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