Looping While a Condition is True

In an earlier post, I talked about using the FOREACH loop to iterate through a collection. The FOREACH loop will execute the code block for each element in the collection. There will be times when you want to execute the same code over and over until a specific condition is met. For that, you would utilize the WHILE and DO…WHILE loops.


WHILE Loop

When writing a WHILE loop, you provide a condition check. As long as that condition check resolves to TRUE, the code block will be executed. After the code block completes, the application will recheck the condition. If it is still TRUE, the code is executed. This action repeats over and over until the condition check resolves to FALSE.

The syntax for a WHILE loop looks like this:


WHILE keyword (condition check)

{

Code Block

}

Here is an example WHILE loop that is written in C#.

 bool quitGame = false;
 
 while (quitGame == false)
 {
 Console.WriteLine("Let's play a game.");
 }

This code will display the message until quitGame becomes something other than false.


Infinite Loops

Before you copy this code into Visual Studio and run it for yourself, I want to point something out. There is nothing in the code block that will ever change the value of quitGame. If the condition check never has the option to resolve to FALSE, the loop will continue forever. When this occurs, it is called an “Infinite Loop” and should be avoided. Infinite loops can cause significant problems on the user’s computer, sometimes requiring them to reboot their system. Always make sure you have code inside your loop that can change the result of the condition check.


We should avoid the creation of an infinite loop by updating the code to something like this:

 while (quitGame == false)
 {
 Console.WriteLine("Let's play a game.");
 
 // Game Code 
 
 Console.WriteLine("Would you like to play again?");
 string answer = Console.ReadLine().Trim().ToLower();
 
 switch (answer)
 {
 case "n":
 case "no":
 case "nope":
 quitGame = true;
  break;
 }
 }

WHILE Loop Examples

You can use a WHILE loop to allow the user to keep entering information until they give you the type of information your application needs.

 Console.WriteLine("How old are you?");
 
 bool isValidInput = false;
 while (isValidInput == false)
 {
 int userAge;
 bool isNumber = int.TryParse(Console.ReadLine(), out userAge);
 
 if (isNumber == false)
 {
 Console.WriteLine("Please enter a valid number.");
 }
 else if (userAge < 3 || userAge > 150)
 {
 Console.WriteLine("I'm pretty sure that's not your real age. Try again.");
 }
 else
 {
 isValidInput = true;
 }
 }

You can also use the input from a user as the condition for your WHILE loop.

 Random random = new Random();
 int number = random.Next(1, 11);
 
 Console.WriteLine("Guess a number from 1 to 10?");
 
 while (int.Parse(Console.ReadLine()) != number)
 {
 Console.WriteLine("Wrong! Guess again.");
 }
 
 Console.WriteLine("You guessed the number.");

While loops are instrumental and quite common when writing applications. The DO…WHILE loop is not as standard, but it is useful in certain situations.


Do…While Loop

A WHILE loop will only execute if the condition check resolves to true. Because of this, there could be situations where the code inside the loop never executes.


In the earlier example, we are checking the value of the quitGame variable before we even run the first instance of our game. The game should run at least one time before we need to worry about quitting.


A DO…WHILE loop will always execute the code inside the loop at least one time. This one-time execution occurs because the condition check is done at the end of each loop, not at the beginning.


The syntax for a DO…WHILE loop looks like this:

DO

{

Code Block

}

WHILE keyword (condition check);

Written in C# code, the loop looks like this:

 bool quitGame = false;
 do
 {
 Console.WriteLine("Let's play a game.");
 
 // Game Code 
 
 Console.WriteLine("Would you like to play again?");
 string answer = Console.ReadLine().Trim().ToLower();
 
 switch (answer)
 {
 case "n":
 case "no":
  case "nope":
 quitGame = true;
 break;
 }
 } while (quitGame == false);

With this example the code to play the game will run one time before the condition is even checked.


DO…WHILE loops also make more sense when you want to implement retry logic to ensure the user enters the type of information your application needs.

 do
 {
 Console.WriteLine("How old are you?");
 
  int userAge;
 bool isNumber = int.TryParse(Console.ReadLine(), out userAge);
 
 if (isNumber == false)
 {
 Console.WriteLine("You have not entered a valid number.");
 }
 else if (userAge < 3 || userAge > 150)
 {
 Console.WriteLine("I'm pretty sure that's not your real age.");
 }
 else
 {
 isValidInput = true;
  }
 }
 while (isValidInput == false);

By updating this logic to use a DO…WHILE loop, I don’t have to ask the user multiple times for the data. The question “How old are you?” will be asked until a valid age is entered.


Nested Loops

When writing complex applications, you will find the need to nest loops within one another. Even the simple examples we have used in the post provide a plausible use case for creating nested loops. We have seen one loop has the user play a guess a number game. We have another loop that asks the user if they would like to play again.


Let’s nest those two loops to create a replayable “guess a number” game.

 bool quitGame = false;
 do
 {
 Console.WriteLine("Let's play a game.");
 
 // Game Code 
 Random random = new Random();
 int number = random.Next(1, 11);
 
 Console.WriteLine("Guess a number from 1 to 10?");
 
 while (int.Parse(Console.ReadLine()) != number)
 {
  Console.WriteLine("Wrong! Guess again.");
 } 
 Console.WriteLine("You guessed the number."); 
 
 Console.WriteLine("Would you like to play again?");
 string answer = Console.ReadLine().Trim().ToLower();
 
 switch (answer)
 {
 case "n":
 case "no":
 case "nope":
 quitGame = true;
 break;
 }
 } while (quitGame == false);

When this application is run, our DO…WHILE loop will allow the game to be played at least one time. The WHILE loop executes until the user guesses the correct number. At that time, we ask the user if they want to play again. As long as they enter anything other than our case matches, the DO…WHILE will run again. This process will continue until the user enters a valid response to quit the game.

33 views0 comments

Recent Posts

See All