In programming there are times that we want to iterate through a set of instructions multiple times or for as long as a condition is met.
For example, let’s say we have a variable named counter with the initial value of 0. We want to run a set of instructions in a program repeatedly for as long as the value of the counter variable is not equal to 1000.
This is where we can use the while loop statement.
Alright, before we get into the details of writing a loop via the while, let’s first see its structure:
while (condition) {
// the code block to be executed
}
while: To create a while loop we start with the keyword while.
`( )`: The parentheses that come after the `while` keyword, is used to declare the condition of the loop. The condition here could be for example as long as the value of a variable is not equal (`==`) to a specific value repeat the loop.
Also the true and false values can be used as the value of the condition. The value ture means the condition is true and so the body of the loop can run. Also the value false means the condition of the loop is false and so the body will never run.
`{ }`: The body of the while loop starts from the opening brace `{` and ends right at the closing brace `}`.
Note: every time the engine executes the body, the condition will be checked again.
Example:
using System;
namespace quickExample
{
public class Program
{
public static void Main(string[] args)
{
char character = 'a';
while(!(character == 'z'))
{
Console.Write(character+", ");
character++;
}
}
}
}
Output:
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y,
As mentioned in the data-type section, char is another integer data-type and so it is possible to apply the ++ operator on a variable of this type.
In this example the value of the character variable is first set to a and next we use this variable as the condition in the while loop. Basically the condition of the loop is to check the character variable and as long as its value is not equal to z, the body of the loop should be iterated.
In another word, until the value of the character variable reaches the value z, the condition of the while loop is true and so the body of that loop will run over and over again.
Note: in the body of the loop we used ++ operator to increase the value of the character variable.
Basically what we did here is to ensure the loop will not run indefinitely!