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
forand open-ended loops withwhiletraverse a string character by character
use
breakandcontinuepurposefullyrecognize and avoid infinite loops