Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 8 / 68

Loops (while statements)

In this lesson you will learn how to repeat work with a while statement in C#, and how to tell it apart from a for statement. This is for anyone searching for "C# while loop how to use".

A while statement repeats as long as its condition holds. The rule of thumb is: use a for loop when you already know the stopping point, and a while loop when you do not know in advance when it will finish.

The sample code initialises int i = 1, repeats while i <= 5, and increases the value by one with i++ inside the loop. You can see the loop exit at the moment the condition becomes false.

A common stumbling block for beginners is forgetting to update the variable that the condition depends on. Miss that update and you get an infinite loop.

In real-world development, while loops are common where the number of repetitions cannot be predicted, such as asking the user again and again until they enter something valid.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)