Iteration

5. Iteration#

Repeating a task is one of the most powerful things a program can do. This chapter covers two fundamental loop structures in C# — for and while — and the patterns that make them correct and readable.

Why this chapter matters

Loops are how programs scale from toy examples to real work:

  • process every element in a collection without copy-pasting code

  • repeat a prompt until the user provides valid input

  • compute sums, products, and counts over arbitrary amounts of data

  • automate tasks that would be impractical to write out by hand

Learning goals

By the end of this chapter, you should be able to:

  • write counted loops with for and open-ended loops with while

  • traverse a string character by character

  • use break and continue purposefully

  • recognize and avoid infinite loops

Chapter flow