
Repeating Program Steps
One of the computer’s 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 ...