Lesson 19

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 calculate bills for a million customers, you would need to write at least a million 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 perform 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 gets the loop ready to start. Usually this part declares and initializes the looping variable.
  • doneTest is a boolean expression that determines when the loop stops. The loop ­continues running as long as this expression is true.
  • next prepares the loop for its next iteration. ...

Get C# 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.