#157 – Iterating Using the while Loop

The while loop allows you to execute a single statement or block of code 0 or more times, continuing to execute while a particular expression evaluates to true.  The expression can be a single boolean variable or a more complicated expression that evaluates to a boolean result.

Here’s an example.

            bool keepPlaying = true;

            // Display trivia until user wants to quit
            while (keepPlaying)
            {
                DisplaySomeTrivia();
                keepPlaying = AskUserIfTheyWantToContinue();
            }

The braces denote the block of code that will be executed repeatedly.  Since the keepPlaying variable starts out true, the code will be executed at least once.  AskUserIfTheyWantToContinue will ask the user if they want to continue and return a true or false value.  So the loop will execute until the user decides to stop.

Another example:

            int numTimesPrinted = 0;

            // Print something out 100 times
            while (numTimesPrinted < 100)
            {
                Console.WriteLine("I will not pull Sally's pigtails");
                numTimesPrinted++;
            }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: