Introduction to while loops
- There are two basic types of decision structures in all programming
languages. We’ve just learned about the first, which is the “selection
structure,” or
ifstatement. This allows the program to choose whether or not to execute a block of code, based on a condition. - The second basic decision structure is the loop, which allows the program to execute the same block of code repeatedly, and choose when to stop based on a condition.
- The while statement executes a block of code repeatedly, as long as a condition is true. You can also think of it as executing the code repeatedly until a condition is false
Example code with a while loop
int counter = 0;
while(counter <= 3)
{
Console.WriteLine("Hello again!");
Console.WriteLine(counter);
counter++;
}
Console.WriteLine("Done");-
After the keyword
whileis a condition, in parentheses:counter <= 3 -
On the next line after the
whilestatement, the curly brace begins a code block. The code in this block is “controlled” by thewhilestatement. -
The computer will repeatedly execute that block of code as long as the condition
counter <= 3is true -
Note that inside this block of code is the statement
counter++, which incrementscounterby 1. So eventually,counterwill be greater than 3, and the loop will stop because the condition is false. -
This program produces the following output:
Hello again! 0 Hello again! 1 Hello again! 2 Hello again! 3 Done
Syntax and rules for while loops
-
Formally, the syntax for a
whileloop is this:while(<condition>) { <statements> } -
Just like with an
ifstatement, the condition is any expression that produces aboolvalue (including aboolvariable by itself) -
When the computer encounters a
whileloop, it first evaluates the condition -
If the condition is false, the loop body (code block) is skipped, just like with an
ifstatement -
If the condition is true, the loop body is executed
-
After executing the loop body, the computer goes back to the
whilestatement and evaluates the condition again to decide whether to execute the loop again -
Just like with an
ifstatement, the curly braces can be omitted if the loop body is just one statement:while(<condition>) <statement> -
Examining the example in detail
-
When our example program executes, it initializes
counterto 0, then it encounters the loop -
It evaluates the condition
counter <= 0, which is true, so it executes the loop’s body. The program displays “Hello again!” and “0” on the screen. -
At the end of the code block (after
counter++) the program returns to thewhilestatement and evaluates the condition again. 1 is less than 3, so it executes the loop’s body again. -
This process repeats two more times, and the program displays “Hello again!” with “2” and “3”
-
After displaying “3”,
counter++incrementscounterto 4. Then the program returns to thewhilestatement and evaluates the condition, butcounter <= 3is false, so it skips the loop body and executes the last line of code (displaying “Done”)
While loops may execute zero times
-
You might think that a “loop” always repeats code, but nothing requires a while loop to execute at least once
-
If the condition is false when the computer first encounters the loop, the loop body is skipped
-
For example, if we initialize
counterto 5 with our previous loop:int counter = 5; while(counter <= 3) { Console.WriteLine("Hello again!"); Console.WriteLine(counter); counter++; } Console.WriteLine("Done");The program will only display “Done,” because the body of the loop never executes.
counter <= 3is false the first time it is evaluated, so the program skips the code block and continues on the next line.
Ensuring the loop ends
-
If the loop condition is always true, the loop will never end, and your program will execute “forever” (until you forcibly stop it, or the computer shuts down)
-
Obviously, if you use the value
truefor the condition, the loop will execute forever, like in this example:int number = 1; while (true) Console.WriteLine(number++); -
If you do not intend your loop to execute forever, you must ensure the statements in the loop’s body do something to change a variable in the loop condition, otherwise the condition will stay true
-
For example, this loop will execute forever because the loop condition uses the variable
counter, but the loop body does not change the value ofcounter:int counter = 0; while(counter <= 3) { Console.WriteLine("Hello again!"); Console.WriteLine(counter); } Console.WriteLine("Done"); -
This loop will also execute forever because the loop condition uses the variable
num1, but the loop body changes the variablenum2:int num1 = 0, num2 = 0; while(num1 <= 5) { Console.WriteLine("Hello again!"); Console.WriteLine(num1); num2++; } Console.WriteLine("Done"); -
It’s not enough for the loop body to simply change the variable; it must change the variable in a way that will eventually make the condition false
-
For example, if the loop condition is
counter <= 5, then the loop body must increase the value ofcounterso that it is eventually greater than 5 -
This loop will execute forever, even though it changes the right variable, because it changes the value in the wrong “direction”:
int number = 10; while(number >= 0) { Console.WriteLine("Hello again!"); Console.WriteLine(number); number++; }The loop condition checks to see whether
numberis 0, andnumberstarts out at the value 10. But the loop body incrementsnumber, which only moves it further away from 0 in the positive direction. In order for this loop to work correctly, we need to decrementnumberin the loop body, so that eventually it will be less than 0. -
This loop will execute forever, even though it uses the right variable in the loop body, because it multiplies the variable by 0:
int number = 0; while (number <= 64) { Console.WriteLine(number); number *= 2; }Since
numberwas initialized to 0,number *= 2does not actually change the value ofnumber: . So the loop body will never make the conditionnumber <= 64false.
-
Principles of writing a while loop
-
When writing a
whileloop, ask yourself these questions about your program:- When (under what conditions) do I want the loop to continue?
- When (under what conditions) do I want the loop to stop?
- How will the body of the loop bring it closer to its ending condition?
-
This will help you think clearly about how to write your loop condition. You should write a condition (Boolean expression) that will be
truein the circumstances described by (1), andfalsein the circumstances described by (2) -
Keep your answer to (3) in mind as you write the body of the loop, and make sure the actions in your loop’s body match the condition you wrote.
While Loop With Complex Conditions
In the following example, a complex boolean expression is used in the while statement. The program gets a value and tries to parse it as an integer. If the value can not be converted to an integer, the program tries again, but not more than three times.
int c;
string message;
int count;
bool res;
Console.WriteLine("Please enter an integer.");
message = Console.ReadLine();
res = int.TryParse(message, out c);
count = 0; // The user has 3 tries: count will be 0, 1, 2, and then we default.
while (!res && count < 3)
{
count++;
if (count == 3)
{
c = 1;
Console.WriteLine("I'm using the default value 1.");
}
else
{
Console.WriteLine("The value entered was not an integer.");
Console.WriteLine("Please enter an integer.");
message = Console.ReadLine();
res = int.TryParse(message, out c);
}
}
Console.WriteLine("The value is: " + c);