While Loop

While is a condition controlled loop. It continues on condition that a certain test is met. In the example below the loop while continue so long as x > 0.

x = 15
y = 0
while x > 0
    y = y + 1
    x = x -y
endwhile
print(y)

The pseudocode here does the following:

  1. A variable called x is created and set to 15
  2. A variable called y is created and set to 0
  3. The while loop checks if x is greater than 0. It is so the code inside the loop will be executed.
    • y will be incremented by 1. So y will be 1.
    • x will be decremented by y. So x will be 15-1 which is 14.
  4. The loop will then check again as to whether x is greater than 0.
  5. It is, so the code inside will be executed again.
  6. This will continue until the while conditon (x > 0) fails.
  7. At this point the code inside the loop will be skipped and the following line of code will be executed.
print(y)

What will be displayed?

Check the trace table to see all values of the given variables x and y, as well as the output.

While True

The following code is an infinite loop. It will keep displaying Hello World and never stop.

while (true)
{
    Console.WriteLine("Hello World!");
}

The following code is also an infinite loop. CheckThis is a boolean variable which is set to true. While (CheckThis) is the same as While(CheckThis == true)

bool CheckThis = true;

while (CheckThis) {
    Console.WriteLine("Hello World!");
}

Do While Loop

The Do While loop will run the code inside the loop before checking the test condition. So in the code below the user will be asked to enter a password once before the password is checked.

string userPwd = "";

do
{
    Console.WriteLine("please enter your password");
    userPwd = Console.ReadLine();
} while (userPwd != "abc")

Do While Loop in Exams

You may see REPEAT UNTIL in the exams for DO WHILE.

text


Getting out of a Loop... Break and Continue

Most loops include many lines of code which need to be executed inside the loop. Find out more about break and continue on W3Schools here.


Want to know more?

Find out more on W3Schools by clicking here.