DEV Community

Cover image for C# Loops: for vs while - When to Use Each (With Real Examples)
Ifedayo Agboola
Ifedayo Agboola

Posted on • Edited on • Originally published at blackscripts.hashnode.dev

C# Loops: for vs while - When to Use Each (With Real Examples)

Stop guessing which loop to use. Here's a simple, real-world guide to choosing between for and while loops in C#.

Stop guessing which loop to use. Here's the simple decision framework.


Ever stared at your code wondering: "Should I use a for loop or while loop here?"

You're not alone. This confusion trips up beginners constantly, and I see experienced developers make the wrong choice too.

Here's the truth: picking the right loop isn't about syntax, it's about intent.

Let me show you exactly when to use each one, with real examples you'll actually encounter.


The Simple Decision Rule

Use for loops when: You know exactly how many times to repeat

Use while loops when: You repeat until some condition changes

That's it. Everything else flows from this.


For Loops: "Do This X Times"

Perfect for countable operations:

Example 1: Processing Arrays

int[] scores = { 95, 87, 92, 78, 88 };

// You know exactly how many elements to process
for (int i = 0; i < scores.Length; i++)
{
    Console.WriteLine($"Student {i + 1}: {scores[i]}%");
}
Enter fullscreen mode Exit fullscreen mode

Example 2: Building Patterns

// Print a 5x5 grid of stars
for (int row = 0; row < 5; row++)
{
    for (int col = 0; col < 5; col++)
    {
        Console.Write("* ");
    }
    Console.WriteLine();
}
Enter fullscreen mode Exit fullscreen mode

Why for works here: You have a clear start (0), clear end (5), and predictable steps.


While Loops: "Do This Until..."

Perfect for dynamic conditions:

Example 1: User Input Validation

string password;
do
{
    Console.Write("Enter password (min 8 characters): ");
    password = Console.ReadLine();
} 
while (password.Length < 8); // Keep asking until valid
Enter fullscreen mode Exit fullscreen mode

Example 2: File Processing

StreamReader reader = new StreamReader("data.txt");
string line;

while ((line = reader.ReadLine()) != null) // Read until end of file
{
    ProcessLine(line);
}
Enter fullscreen mode Exit fullscreen mode

Why while works here: You don't know in advance how many iterations you'll need.


Common Mistakes (And How to Fix Them)

Mistake 1: Using while for Simple Counting

// ❌ Awkward and error-prone
int i = 0;
while (i < 10)
{
    Console.WriteLine(i);
    i++; // Easy to forget this!
}

// ✅ Much clearer intent
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(i);
}
Enter fullscreen mode Exit fullscreen mode

Mistake 2: Using for for Unknown Iterations

// ❌ Feels forced and unnatural
for (string input = ""; input != "quit"; input = Console.ReadLine())
{
    ProcessCommand(input);
}

// ✅ Expresses intent clearly
string input;
while ((input = Console.ReadLine()) != "quit")
{
    ProcessCommand(input);
}
Enter fullscreen mode Exit fullscreen mode

Real-World Decision Making

Here are scenarios you'll actually face:

Scenario Best Loop Why
Process every item in a list for Known count
Wait for user to enter "quit" while Unknown duration
Generate 100 random numbers for Exact count needed
Read lines until file ends while File size unknown
Display a countdown timer for Known start/end
Retry failed network requests while Success unpredictable

Challenge: Put Your Skills to the Test

Here's a practical problem you might encounter in real projects:

Write a function that counts how many times a character appears in a string:

// Example: CountChar("hello world", 'l') should return 3
public static int CountChar(string text, char target)
{
    // Your solution here
}
Enter fullscreen mode Exit fullscreen mode

Try solving this with both loop types. Which feels more natural?

Spoiler alert: Both work, but one will feel obviously better once you try them.

You can also practice similar problems on LeetCode here.


Pro Tips for Loop Mastery

1. Read Your Code Aloud

  • for: "For each item in this collection..."

  • while: "While this condition is true..."

The right choice usually sounds more natural.

2. Consider Future Maintenance

// This screams "I'm processing a fixed collection"
for (int i = 0; i < users.Count; i++)
{
    ValidateUser(users[i]);
}

// This says "I'm waiting for something to happen"
while (!connectionEstablished)
{
    TryConnectToServer();
    Thread.Sleep(1000);
}
Enter fullscreen mode Exit fullscreen mode

3. Watch Out for Infinite Loops

// ❌ Infinite loop - forgot to increment
int i = 0;
while (i < 10)
{
    Console.WriteLine(i);
    // Missing: i++;
}

// ✅ For loop prevents this mistake
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(i);
}
Enter fullscreen mode Exit fullscreen mode

The Bottom Line

Stop overthinking it:

  • Know your iterations in advance? → Use for

  • Waiting for something to change? → Use while

  • Processing collections? → Usually for (or foreach)

  • User input or external conditions? → Usually while

The "right" loop makes your code easier to read, understand, and maintain. Your future self (and teammates) will thank you.


Your turn: Which loop type do you reach for most often? Share your reasoning in the comments!

CSharp #Programming #Loops #CleanCode

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.