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 lesson’s
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 won’t 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