Featured Articles:

Friday, September 18, 2026

Loops in Coding Explained: for, while, foreach, and do-while in C#

Today is a beautiful day to talk about one of the most useful tools in your programming toolbox: loops in coding. I'm not talking about the Update of Fixed update loops, or Coroutines, for that matter. And why today specifically? Well, I don't know - had to do an intro - and it sounded pretty good.

We're going over the 4 major types of loops you need to know. If you've ever found yourself copy-pasting the same line of code five, ten, or twenty times just to do the same thing over and over, you're about to feel a little silly, because that's exactly what loops are built to solve. 

Let's dive in!


Fundamentally, What Is A Loop In Programming?

A loop is a block of code that repeats itself until a condition tells it to stop. 

That's the entire concept. Instead of writing the same instruction over and over by hand, you write it once, wrap it in a loop, and let the computer handle the repetition for you. Think about spawning 10 enemies in a wave, checking every item in a player's inventory, or updating the position of every bullet on screen. Doing any of that manually, one line per enemy or per bullet, would be a nightmare to write and an even bigger nightmare to maintain. A loop in programming takes care of all of it in a handful of lines.

start  →  run the code inside the loop  →  check the condition  →  repeat or stop

Every loop, no matter which type you use, follows that same basic shape. The differences between loop types come down to *how* they check that condition and *when* they decide to stop.

1. The 'for' Loop: When You Know How Many Times

The for loop is the one you'll reach for constantly, especially when you already know exactly how many times you want something to repeat. Want to spawn exactly 10 enemies? A for loop is built for that.

for (int i = 0; i < 10; i++)
{
    Debug.Log("Spawning enemy number " + i);
}

Break that down piece by piece, because the syntax trips up a lot of beginners at first:

  • int i = 0 - the starting point. This creates a counter variable, usually named i, and sets it to zero.
  • i < 10 - the condition. As long as this is true, the loop keeps running. The moment it's false, the loop stops.
  • i++ - the update. This runs after every single loop cycle, incrementing i by one.

So that loop runs with i equal to 0, 1, 2, all the way up to 9, for a total of 10 runs, then stops as soon as i hits 10. This exact pattern, for loop in C#, is everywhere in Unity code, from spawning objects to looping through arrays.




2. The 'while' Loop: The Loop That Keeps On Looping: When You Don't Know How Many Times

Sometimes you don't know in advance how many times something needs to repeat, you just know it should keep going until some condition becomes false. That's exactly what a while loop is for.

int health = 100;

while (health > 0)
{
    health -= 10;
    Debug.Log("Health is now: " + health);
}

This keeps subtracting 10 from health and logging the result, for as long as health stays above zero. Unlike a for loop, there's no built-in counter, you're just watching a condition and reacting to it. A while loop is a great fit for things like "keep enemies spawning until the player reaches the boss room" or "keep waiting until an asset finishes loading."

Warning!

One warning that every beginner needs to hear at least once: if that condition never becomes false, you've written an infinite loop, and your game (or your editor/system) will freeze! 

Always make sure something inside the loop is actually working toward making the condition false eventually.




3. The 'foreach' Loop: Looping Through Collections

This one's less about counting and more about visiting every item in a collection, like an array or a list, one at a time. If you're working with an inventory system, a list of enemies, or any array data type, foreach is usually the cleanest option.

string[] items = { "Sword", "Shield", "Potion" };

foreach (string item in items)
{
    Debug.Log("You have a " + item);
}

No counter variable, no manually tracking an index, foreach just hands you each item one by one until it's gone through the whole collection. It's less flexible than a regular for loop (you can't easily skip around or go backwards), but for straightforward "do this for every item" situations, it reads far more clearly.


4. 'do-while': The Loop That Always Runs At Least Once

A do-while loop is a close cousin of the regular while loop, with one key difference: it checks the condition *after* running the code inside, not before. That guarantees the loop body runs at least once, even if the condition was already false to begin with.

int attempts = 0;

do
{
    attempts++;
    Debug.Log("Attempt number: " + attempts);
} while (attempts < 3);

This pattern shows up in situations like retry logic, where you want to attempt something at least one time no matter what, then keep retrying based on a condition. It's less common than the other three, but worth knowing it exists. 


To be honest, I've never used it in my own project. I just never had a real use case for it. This is perhaps the case for more programmers - yet I did want to mention it.


break and continue: Controlling the Flow Mid-Loop

Sometimes you need to exit a loop early, or skip just one cycle without stopping the whole thing. That's where break and continue come in.

  • break - immediately exits the loop entirely, no matter what the original condition says.
  • continue - skips the rest of the current cycle and jumps straight to the next one.
for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        break; // stop the loop completely once i hits 5
    }
    Debug.Log("Number: " + i);
}

Useful example: searching through a list of enemies for the closest one, then breaking out the moment you find a match instead of wastefully checking every remaining enemy in the list.


So Which Loop Should You Actually Use?

Here's the no-fluff version, the gut check you can run through in your head:

  • Know exactly how many times to repeat → for loop
  • Repeat until some condition changes, count unknown → while loop
  • Need to run the code at least once no matter what → do-while
  • Going through every item in an array or list → foreach
  • Need to exit early or skip a cycle → break or continue

Picking the right loop in programming isn't about memorizing syntax, it's about asking "do I know how many times this needs to run, or am I just watching for a condition to change?" That single question points you at the right loop almost every time. This applies whether you're writing a simple for loop in C# or reaching for a while loop instead.


Wrapping Up

Loops are one of those concepts that feel a little abstract right up until you write your first one that actually works, then suddenly half the repetitive code you used to copy-paste by hand just... isn't needed anymore. Get comfortable with for, while, and foreach, know that do-while exists for the rare cases that need it, and you've got one of the most powerful tools in programming fully in your hands. 


 ~happy Coding!

No comments:

Post a Comment