WHAT'S NEW?
Loading...

Meringkas Exchanging the values of two variables"


Problem

  •  Given two variables a and b, exchange the values assigned to them.

Algorithm development

Consider that the variables a and b are assigned values as outlined below. That is:
Starting Configuration

Configuration above means that on variable a contains value 721, and variable b contains value 463, Now our task is find a way how to make variable a contains 463 and variable b contains 721. Like this:

Target Configuration

To exchange the value of a variables, we can use the assignment operator:

Assignment operator

":=" is the assignment operator. ":=" in (1) means value of variable b copied and change the original value of variable a .
Lets practice!

This is the started configuration:


then after execution of the assignment a:=b; we have:

After execution a:=b

Assignment (1) change the value of variable a with copy value of variable b. and value of variable b still same just like the starting configuration. and when we execution assignment "b:=a" it will end up like this:

After execution b:=a


Still same.. Why? Because after executed assignment "a:=b" value of variable a is changed. Already changed. Result is after execute assignment "b:=a" original value of variable a lost. And it doesn't represent solution we are seeking.

To solve this problem, we need to find a way of not lost the original value of variable a when we make assignment "a:=b". That way is, we must introduce a new variable, or we can call, a temporary variable. Name is variable t. this variable needed to copy the original value of variable a, for temporary, before executing assignment "a:=b". The Step to do that is:

Assignment for variable t

after two steps above, result is:

After execution "t:=a" and "a:=b"

than last time, we doesn't lost value of variable a, because that value saved on variable t. Now, we just need to execute assignment :

Assignment to target configuration

After execution "b:=t" assignment, we have our target configuration:

Target configuration
We can see that a and b have now been interchanged as required. Now we can outlined exchange procedure.


0 komentar:

Posting Komentar