Introduction to loops
One common problem software engineers face when building software is repetition. Sometimes, they need to build code that needs to do repetitive tasks, such as reading from a database or analyzing blocks of text. This type of flow control is called iteration. Loops are blocks of code that run repeatedly until a condition, such as a Boolean value, is met. The loop continually runs when the condition is true and stops when it becomes false. C# has a few different types of loops, also called iterators, but this section will focus on the for
and while
loops. You can read more about the other loops by looking at the links provided in the Further reading section.
Using a for loop
The syntax of a for
loop includes three parts, as shown here:
Figure 7.3 – Identifying the different parts of a for loop
The initializer creates and sets the initial starting value of a variable that can be used within the code block of the for
loop...