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 its 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 dont want to explain
why the algorithm works because its 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
Break and Continue
235
A do loop always executes its code at least once because it doesn’t check its con-
dition until the end. Often that feature is why you should pick a
do loop over a
while loop or vice versa. If you might not want the loop to execute even once,
use a
while loop. If you need to run the loop once before you can tell whether
to stop, use a
do loop.
BREAK AND CONTINUE
The break and continue statements change the way a loop works.
The
break statement makes the code exit the loop immediately without executing any more state-
ments inside the loop.
For example, the following code searches the selected items in a
ListBox for the value Carter. If it
nds that value, it sets the Boolean variable
carterSelected to true and breaks out of the loop. If
the
ListBox has many selected items, breaking out of the loop early may let the program skip many
loop iterations and save some time.
// See if Carter is one of the selected names.
bool carterSelected = false;
foreach (string name in namesListBox.SelectedItems)
{
if (name == “Carter”)
{
carterSelected = true;
break;
}
}
MessageBox.Show(carterSelected.ToString());
The continue statement makes a loop jump to its looping statement early, skipping any remaining
statements inside the loop after the
continue statement.
For example, the following code uses a
foreach loop to display the square roots of the numbers
in an array. The
Math.Sqrt function cannot calculate the square root of a negative number so, to
avoid trouble, the code checks each value. If it finds a value less than zero, it uses the
continue
statement to skip the rest of that trip through the loop so it doesn’t try to take the number’s square
root. It then continues with the next number in the array.
// Display square roots.
float[] values = { 4, 16, -1, 60, 100 };
foreach (float value in values)
{
if (value < 0) continue;
Console.WriteLine(string.Format(“The square root of {0} is {1:0.00}“,
value, Math.Sqrt(value)));
}
596906c19.indd 235 4/7/10 12:33:23 PM
236
LESSON 19 Repeating pRogRam StepS
The following text shows this program’s results:
The square root of 4 is 2.00
The square root of 16 is 4.00
The square root of 60 is 7.75
The square root of 100 is 10.00
The break and continue statements make loops work in nonstandard ways and
sometimes that can make the code harder to read, debug, and maintain. Use them
if it makes the code easier to read, but ask yourself whether there’s another simple
way to write the loop that avoids these statements. For example, the following
code does the same things as the previous code but without a
continue statement:
// Display square roots.
float[] values = { 4, 16, -1, 60, 100 };
foreach (float value in values)
{
if (value >= 0)
{
Console.WriteLine(string.Format(“The square root of {0} is
{1:0.00}“,
value, Math.Sqrt(value)));
}
}
TRY IT
In this Try It, you make the simple login form shown in Figure 19-1.
When the program’s startup form loads, it enters a loop that makes it
display this form until the user enters the correct username and pass-
word or clicks the Cancel button.
You can download the code and resources for this Try It from the book’s web
page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find
them in the Lesson19 folder in the download.
Lesson Requirements
Build a main form that displays a success message.
Build the login dialog shown in Figure 19-1.
In the main form’s
Load event handler, create an instance of the login dialog. Then enter a
while loop that displays the dialog and doesn’t stop until the user enters a username and
password that match values in the code. If the user clicks Cancel, close the main form.
FIGURE 191
596906c19.indd 236 4/7/10 12:33:24 PM
Try It
237
Hints
Use a Boolean variable named
tryingToLogin to control the loop. Initialize it to true before the
loop and set it to false when the user either cancels or enters the right username and password.
To decide whether the user entered a valid username and password, compare them to the
strings “User” and “Secret.” (A real application would validate these values with a database
or by using some other authentication method.)
Step-by-Step
Build a main form that displays a success message.
1. Place labels on the form to display the message.
Build the login dialog shown in Figure 19-1.
1. Create the controls shown in Figure 19-1.
2. Set the password TextBox’s PasswordChar property to X.
In the main form’s
Load event handler, create an instance of the login dialog. Then enter a
while loop that displays the dialog and doesn’t stop until the user enters a username and
password that match values in the code. If the user clicks Cancel, close the main form and
break out of the loop.
1. The following code shows one possible solution:
// Make the user log in.
private void Form1_Load(object sender, EventArgs e)
{
// Create a LoginForm.
LoginForm frm = new LoginForm();
// Repeat until the user successfully logs in.
bool tryingToLogin = true;
while (tryingToLogin)
{
// Display the login dialog and check the result.
if (frm.ShowDialog() == DialogResult.Cancel)
{
// The user gives up. Close and exit the loop.
this.Close();
tryingToLogin = false;
}
else
{
// See if the user entered valid values.
if ((frm.usernameTextBox.Text == “User”) &&
(frm.passwordTextBox.Text == “Secret”))
{
// Login succeeded. Stop trying to log in.
tryingToLogin = false;
}
596906c19.indd 237 4/7/10 12:33:24 PM
238
LESSON 19 Repeating pRogRam StepS
else
{
// Login failed. Display a message and let the loop continue.
MessageBox.Show(“Invalid username and password.”);
}
}
}
// If we get here, we’re done trying to log in.
}
Please select Lesson 19 on the DVD to view the video that accompanies this lesson.
EXERCISES
1. Make a program that calculates the sum 1 + 2 + 3 + … + N for a number N entered by the
user.
2. Make a program that calculates the Nth Fibonacci number for a number N entered by the
user. The Fibonacci sequence is defined by:
Fibonacci(0) = 0
Fibonacci(1) = 1
Fibonacci(N) = Fibonacci(N - 1) + Fibonacci(N - 2)
Hint: Use a loop. Define variables fibo1, fibo2, and fiboN outside the loop. Inside the
loop, make the variables hold Fibonacci(N - 1), Fibonacci(N - 2), and Fibonacci(N). (To test
your code, Fibonacci(10) = 55 and Fibonacci(20) = 6,765.)
3. Make a program that lets the user enter test scores into a ListBox. After adding each score,
display the minimum, maximum, and average values. (Hint: Before you start the loop, initial-
ize
minimum and maximum variables to the value of the first score. Then loop through the list
revising the variables as needed.)
4. Copy the program you built for Lesson 14’s
Exercise 1 (or download Lesson 14’s version
from the book’s web site) and add the List
Items button shown in Figure 19-2. When
the user clicks the button, display the items
and their values in the Console window
as a semicolon-separated list similar to
the following:
**********
Pencil;$0.10;12;$1.20;
Pen;$0.25;12;$3.00;
Notebook;$1.19;3;$3.57;
**********
FIGURE 192
596906c19.indd 238 4/7/10 12:33:24 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.220.83