Lets begin the summary!
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 |
Algorithm description
- Save original value of a into t
- Assign original value of b into a
- Assign to b original value of a that is saved in t
Pascal Implementation
Notes on design
- The use of an intermediate temporary variable allows the exchange of two variable proceed correctly.
- Any stage in a computation variable always assumes the value dictated by the most recent assignment made to that variable.
- Working through the mechanism with a particular example can be a useful way of detecting design faults.
Tidak ada komentar:
Posting Komentar