A Quick Introduction to While Loops in C#

Dennisse Pagán Dávila
2 min readAug 12, 2021

Note: In this article, we’ll be taking a look at while loops, and their variation, do-loops.

What is a While Loop?

A While Loop is a programming structure that is used to repeat a line or block of code until a condition is met. While loops are often used within coroutines, which can prevent the dreadful infinite loops from happening.

While Loop Syntax Flowchart

Syntax:

  • Condition: This is the requirement needed to run the loop, as long as the condition is true, the loop will run.
  • Modifier or Update: It is extremely important to have a modifier for the condition variable or the loop will become infinite. The only right way to run an infinite while loop is through the use of coroutines. Since coroutines allow the program to breathe you can effectively make a coroutine that will run forever without the program crashing.

What is a Do-While Loop?

Essentially, a do-while loop is the same as a while loop with the exception of having the code always execute at least once.

Do-While Loop Syntax Flowchart

Syntax:

The syntax follows the same logic of a while look, however, it has some key differences.

  • The “do” keyword is the reason why the loop will always execute at least once since it is essentially prioritizing the action before the condition. Should the condition be false after the first default run, the loop will stop.
  • Another notable part of the syntax is the positioning of the “while” in the loop. It may feel counterintuitive to some programmers, especially new ones, but it is traditional to place the while keyword directly beside the closing bracket of the do-loop segment.

In the next article, I will be tackling more Core Programming challenges from GameDevHQ! The last one had us randomizing Enemy variants!

--

--

Dennisse Pagán Dávila

Software Engineer that specialize in Game Development. Currently looking for new opportunities. LinkedIn: https://rb.gy/xdu8nu