Repeating Program Steps
One of the computers greatest strengths is its ability to perform the exact same calculation
again and again without getting bored or making careless mistakes. It can calculate the average
test scores for a dozen students, print a hundred advertisements, or compute the monthly bills
for a million customers with no trouble or complaining.
The lessons you’ve read so far, however, don’t tell you how to do these things. So far every step
the computer takes requires a separate line of code. To add up 10 numbers, you would need to
write 10 lines of code.
In this lesson you learn how to make the computer execute the same lines of code many
times. You learn how to loop through arrays and collections of items to take action or per-
form calculations on them.
The following sections describe the kinds of loops provided by C#. The final section describes
two statements you can use to change the way a loop works:
break and continue.
FOR LOOPS
A for loop uses a variable to control the number of times it executes a series of statements.
The
for loop’s syntax is as follows:
for (initialization; doneTest; next)
{
statements...
}
Where:
initialization
This statement gets the loop ready to start. Often this part declares
and initializes the looping variable.
doneTest
This is a Boolean expression that determines when the loop stops. The
loop continues running as long as this expression is true.
19
596906c19.indd 229 4/7/10 12:33:21 PM
230
LESSON 19 Repeating pRogRam StepS
next
This statement prepares the loop for its next iteration. Often this increments the
looping variable declared in the
initialization.
statements
These are the statements that you want the loop to execute.
Note that none of the
initialization, doneTest, or next statements are required, although they
are all used by the simplest kinds of
for loops.
For example, the following code displays the numbers 0 through 9 followed by their squares in the
Console window:
for (int i = 0; i < 10; i++)
{
int iSquared = i * i;
Console.WriteLine(string.Format(“{0}: {1}“, i, iSquared));
}
In this code the initialization statement declares the variable i and sets it to 0, the next statement
adds 1 to
i, and the doneTest keeps the loop running as long as i < 10.
Here’s a slightly more complicated example that calculates factorials. The program converts the
value selected in the
NumericUpDown named numberNumericUpDown into a long integer and saves it
in variable
n. It initializes the variable factorial to 1 and then uses a loop to multiply factorial
by each of the numbers between 2 and
n. The result is 1 * 2 * 3 * … * n, which is n!.
// Get the input value N.
long n = (long)numberNumericUpDown.Value;
// Calculate N!.
long factorial = 1;
for (int i = 2; i <= n; i++)
{
checked
{
factorial *= i;
}
}
// Display the result.
resultTextBox.Text = factorial.ToString();
You may recall that Lesson 16 used code to calculate Fibonacci numbers, and in that lessons
Exercise 1 you calculated factorials. Those programs used 20 lines of code to calculate and store
20 values that the program then used as a kind of lookup table.
The factorial calculation code shown here is more efficient. It doesn’t require a large array to hold
values. It also doesn’t require that you know ahead of time how many values you might need to
calculate (20 for the earlier programs), although the factorial function grows so quickly that this
program can only calculate values up to 20! before the result wont fit in a
long.
The for loop is often the best choice if you know exactly how many times you
need the loop to execute.
596906c19.indd 230 4/7/10 12:33:21 PM
Foreach Loops
231
FOREACH LOOPS
A foreach loop executes a block of code once for each item in an array or list. The syntax of the
foreach loop is as follows:
foreach (variableDeclaration in items)
{
statements...
}
Where:
variableDeclaration
This piece declares the looping variable. Its type must be the same
as the items in the array or list.
items
This is the array or list of items over which you want to loop.
statements
These are the statements that you want the loop to execute.
For example, the following code calculates the average of the test scores stored in the
ListBox named
scoresListBox. Note that the ListBox must contain integers or something the program can implicitly
convert into an integer or else the program will crash.
// Make sure the list isn’t empty.
if (valuesListBox.Items.Count < 1)
{
MessageBox.Show(“There are no items to average.”);
}
else
{
// Add up the values.
int total = 0;
foreach (int value in valuesListBox.Items)
{
total += value;
}
// Calculate the average.
float average = (float)total / valuesListBox.Items.Count;
// Display the result.
MessageBox.Show(“Average: “ + average.ToString(“0.00”));
}
The code creates a variable named total and sets it equal to 0. It then loops through the items in
the
ListBox, adding each value to total.
This code loops over the items in a ListBox treating those items as integers. If
the
ListBox contains something other than integers, the program will crash.
596906c19.indd 231 4/7/10 12:33:22 PM
232
LESSON 19 Repeating pRogRam StepS
The code finishes by dividing the total by the number of items in the ListBox.
If you need to perform some operation on all of the items in an array or list, a
foreach loop is often your best choice.
WHILE LOOPS
A while loop executes as long as some condition is true. The syntax for a while loop is as follows:
while (condition)
{
statements...
}
Where:
condition
The loop executes as long as this Boolean expression is true.
statements
These are the statements that you want the loop to execute.
For example, the following code calculates a number’s prime factors:
// Find the number’s prime factors.
private void factorButton_Click(object sender, EventArgs e)
{
// Get the input number.
long number = long.Parse(numberTextBox.Text);
// Find the factors.
string result = “1”;
// Consider factors between 2 and the number.
for (long factor = 2; factor <= number; factor++)
{
// Pull out as many copies of this factor as possible.
while (number % factor == 0)
{
result += “ x “ + factor.ToString();
number = number / factor;
}
}
// Display the result.
resultTextBox.Text = result;
}
The code starts by getting the user’s input number. It builds a result string and initializes it to 1.
596906c19.indd 232 4/7/10 12:33:22 PM
Do Loops
233
Next the code users a for loop to consider the numbers between 2 and the user’s number as
possible factors.
For each of the possible factors, it uses a
while loop to remove that factor from the number. As long
as the factor divides evenly into the remaining number, the program adds the factor to the result and
divides the user’s number by the factor.
The code finishes by displaying its result.
Loops that use incrementing integers to decide when to stop are often easier
to write using
for loops instead of while loops. A while loop is particularly
useful when the stopping condition occurs at a less predictable time, as in the
factoring example.
DO LOOPS
A do loop is similar to a while loop except it checks its stopping condition at the end of the loop
instead of at the beginning. The syntax of a
do loop is as follows:
do
{
statements...
} while (condition);
Where:
statements
These are the statements that you want the loop to execute.
condition
The loop continues to execute as long as this Boolean expression is true.
The following code uses a
do loop to calculate the greatest common divisor (GCD) of two numbers,
the largest number that divides them both evenly:
// Calculate GCD(A, B).
private void calculateButton_Click(object sender, EventArgs e)
{
// Get the input values.
long a = long.Parse(aTextBox.Text);
long b = long.Parse(bTextBox.Text);
// Calculate the GCD.
long remainder;
do
{
remainder = a % b;
if (remainder != 0)
596906c19.indd 233 4/7/10 12:33:22 PM
..................Content has been hidden....................

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