Fundamentals of Computer Programming with C# HTML version

Chapter 6. Loops
In This Chapter
In this chapter we will examine the loop programming constructs through
which we can execute a code snippet repeatedly. We will discuss how to
implement conditional repetitions (while and do-while loops) and how to
work with for-loops. We will give examples of different possibilities to define
loops, how to construct them and some of their key usages. Finally, we will
discuss the foreach-loop construct and how we can use multiple loops placed
inside each other (nested loops).
What Is a "Loop"?
In programming often requires repeated execution of a sequence of
operations. A loop is a basic programming construct that allows repeated
execution of a fragment of source code. Depending on the type of the loop,
the code in it is repeated a fixed number of times or repeats until a given
condition is true (exists).
Loops that never end are called infinite loops. Using an infinite loop is rarely
needed except in cases where somewhere in the body of the loop a break
operator is used to terminate its execution prematurely. We will cover this
later but now let’s look how to create a loop in the C# language.
While Loops
One of the simplest and most commonly used loops is while.
while (condition)
loop body;
In the code above example, condition is any expression that returns a
Boolean resulttrue or false. It determines how long the loop body will
be repeated and is called the loop condition. In this example the loop body
is the programming code executed at each iteration of the loop, i.e. whenever
the input condition is true. The behavior of while loops can be represented by
the following scheme: