Skip to main content

While Loops

A while loop repeats a block of code as long as a condition is true. Use it when you don't know in advance how many times something should repeat, for example:

  • Keep playing until the last level is completed.
  • Keep rolling a die until you roll a 1.
  • Keep asking for input until it's valid.

Diagram of a while loop

Syntax​

The structure of a while loop is very similar to an if statement:

while ( condition )
{
// code block
}
  1. The condition is checked before each pass.
  2. If it's true, the code block runs, then the program jumps back to step 1.
  3. If it's false, the block is skipped and execution continues after it.

Because the condition is checked first, the block may run zero times.

while

⚠️ Avoid infinite loops. Something inside the loop must eventually make the condition false. Otherwise, the loop never ends (e.g. as shown above)

Example 1: Phone Lock​

Keep asking for the password until the user enters the correct one.

Pseudocode​

  1. Ask the user for the password.
  2. While the entered password is incorrect:
    • Show an error and ask again.
  3. Unlock the screen.

Flowchart​

while

C# Program​

const string SysPassword = "strong password";
string inputPassword;

Console.Write("Enter password to unlock: ");
inputPassword = Console.ReadLine();

while (inputPassword != SysPassword)
{
Console.Write("Incorrect. Try again: ");
inputPassword = Console.ReadLine();
}

Console.WriteLine("Unlocking screen");

2. System Update​

Ask the user to install updates, and repeat until they enter Y or N.

Flowchart​

Flowchart

C# Program​

Console.Write("Install system updates? [Y/N] ");
string selection = Console.ReadLine();

while (selection != "Y" && selection != "N")
{
Console.Write("Invalid selection. Type Y or N: ");
selection = Console.ReadLine();
}

if (selection == "Y")
{
Console.WriteLine("Starting updates. Don't turn off your machine.");
}
else
{
Console.WriteLine("System is out of date!");
}

selection is overwritten on each pass, so once the loop ends, it's guaranteed to be either Y or N.

References​

Bultena, Sandra and Youmna Badawy. "While Loop." 420-SN1 Notes, John Abbott College, john-abbott-college.github.io/SN1-Notes/topics/s/08_loops/02_while_loop/02_while_loop

Buschinelli, Mauricio. "420-1P6 - Week 7" John Abbott College, Fall 2023.