C# can repeat a code block with a while loop. The while loop repeats code until a condition is true.

While loops are used when you are not sure how long code should be repeated. Think of a tv that should continue its function until a user presses the off button.

While loops in C#

Example

The program below is an example of a while loop in csharp.
It will repeat until a condition is true, which could be forever.

The code block can contain anything, from statements to function calls.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;

namespace Loops {
class Program {
static void Main(string[] args) {
int i = 1;
int max = 20;

while (i < max) {
Console.WriteLine("value of i: {0}", i);
i++;
}
Console.ReadLine();
}
}
}

In the example it repeats the code block until variable i is greater than max.
You must always increment the iterator (i), otherwise the while loop repeats forever.

The code block can be as many lines as you want, in this example its just one line of code that gets repeated.

Exercises

  1. How does a while loop differ from a for loop?