234
LESSON 19 Repeating pRogRam StepS
{
a = b;
b = remainder;
}
} while (remainder > 0);
resultTextBox.Text = b.ToString();
}
Notice that the variable remainder used to end the loop is declared outside of
the loop even though it doesn’t really do anything outside of the loop. Normally
to restrict scope as much as possible, you would want to declare this variable
inside the loop if you could.
However, the end test executes in a scope that lies outside of the loop, so any
variables declared inside the loop are hidden from it.
It’s important that any loop eventually ends, and in this code it’s not completely obvious why that
happens. It turns out that each time through the loop (with the possible exception of the first time),
a and b get smaller. If you run through a few examples, you’ll be able to convince yourself.
If the loop runs long enough,
b eventually reaches 1. At that point b must evenly divide a no mat-
ter what
a is so the loop ends. If b does reach 1, then 1 is the greatest common divisor of the user’s
original numbers and those numbers are called relatively prime.
EUCLID’S ALGORITHM
This algorithm was described by the Greek mathematician Euclid (circa 300 BC),
so it’s called the Euclidean algorithm or Euclid’s algorithm. I don’t want to explain
why the algorithm works because it’s nontrivial and irrelevant to this discussion
of loops (you can find a good discussion at
primes.utm.edu/glossary/xpage/
EuclideanAlgorithm.html
), but I do want to explain what the code does.
The code starts by storing the user’s input numbers in variables
a and b. It then
declares variable
remainder and enters a do loop.
Inside the loop, the program calculates the remainder when you divide
a by b.
If that value is not 0 (that is,
b does not divide a evenly), then the program sets
a = b and b = remainder.
Now the code reaches the end of the loop. The
while statement makes the loop end
if
remainder is 0. At that point, b holds the greatest common divisor.
You may want to step through the code in the debugger to see how the values change.
596906c19.indd 234 4/7/10 12:33:23 PM