Professional Documents
Culture Documents
In the last lesson, you learned how to create a simple loop using the goto statement. I advised you
that this is not the best way to perform loops in C#. The information in this lesson will teach you the
proper way to execute iterative logic with the various C# looping statements. Its goal is to meet the
following objectives:
Learn the while loop.
Learn the do loop.
Learn the for the loop.
Learn the for each loop.
Complete your knowledge of the break statement.
Teach you how to use the continue statement.
The while Loop
A while loop will check a condition and then continues to execute a block of code as long as the
condition evaluates to a boolean value of true. Its syntax is as follows: while (<boolean expression>)
{ <statements> }. The statements can be any valid C# statements. The boolean expression is
evaluated before any code in the following block has executed. When the boolean expression
evaluates to true, the statements will execute. Once the statements have executed, control returns
to the beginning of the while loop to check the boolean expression again.
When the boolean expression evaluates to false, the while loop statements are skipped and
execution begins after the closing brace of that block of code. Before entering the loop, ensure that
variables evaluated in the loop condition are set to an initial state. During execution, make sure you
update variables associated with the boolean expression so that the loop will end when you want it
to. Listing 4-1 shows how to implement a while loop.
Listing 4-1. The While Loop: WhileLoop.cs
using System;
class WhileLoop
{
public static void Main()
{
int myInt = 0;
class DoLoop
{
public static void Main()
{
string myChoice;
do
{
// Print A Menu
Console.WriteLine("My Address Book\n");
class ForLoop
{
public static void Main()
{
for (int i=0; i < 20; i++)
{
if (i == 10)
break;
if (i % 2 == 0)
continue;
class ForEachLoop
{
public static void Main()
{
string[] names = {"Cheryl", "Joe", "Matt", "Robert"};