HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to C#VariablesData TypesOperatorsStringsListsConditions (if / else)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ String
📚 List & Dictionary
🔀 Condition & Loop
🧩 Function
C#›Loops (for / while)

Loops (for / while)

Counting with for, iterating lists with foreach, conditional repetition with while.

Simple enough for a 5-year-old to understand

for loop

Example code
1
using System;
2
for (int i = 1; i <= 3; i++) {
from 1 to 3 (inclusive).
Loopfrom 1 to 3 (inclusive).
3
Console.WriteLine(i);
1, 2, 3
Output / Input1, 2, 3
4
}
LoopOutput / Input
💡 Hint: i++ increases i by 1 in each iteration.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Print the numbers from 1 to 5 vertically using a for loop.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

There are four loop formats in C#: for, foreach, while, and do-while. foreach is the default way to traverse a collection — you cannot make index errors and it clearly shows intent.

For foreach to work, it is sufficient for the collection to be iterable; that is why arrays, List, Dictionary, and custom structures you write are traversed with the same syntax. The mechanism behind it is a single interface.

C# has a powerful alternative to loops: LINQ. Instead of writing a loop to filter, transform, or aggregate a collection, you use chained methods. The result is shorter and its intent is clearer.

What you will learn

  • traversing collections with foreach
  • the for loop and counter logic
  • the difference between while and do-while
  • Using break and continue
  • Nested loops
  • using expressions instead of loops with LINQ

When to use?

If you are processing all elements of a collection, use foreach. If you need an index, are traversing backward, or the step size is other than one, for is required.

do-while is used when the body MUST run AT LEAST ONCE: such as showing a menu, asking until valid input is received.

Common mistakes

Wrong

int[] nums = { 1, 2, 3 };
for (int i = 0; i <= nums.Length; i++) {
    Console.WriteLine(nums[i]);
}

Since less-than-or-equal is used in the condition, the loop runs one extra time and exceeds the array bounds on the last round; you get an "IndexOutOfRangeException". In array loops, the condition should always be strictly less than.

Correct

int[] nums = { 1, 2, 3 };
foreach (int n in nums) {
    Console.WriteLine(n);
}

Wrong

int i = 0;
while (i < 5) {
    Console.WriteLine(i);
}

Since the counter never increments, the condition always stays true and the program enters an infinite loop. When using while, it is mandatory to ensure there is a change affecting the condition inside the loop.

Correct

int i = 0;
while (i < 5) {
    Console.WriteLine(i);
    i++;
}

Wrong

var items = new List<int> { 1, 2, 3 };
foreach (var item in items) {
    items.Add(item * 2);
}

Adding elements to a collection while traversing throws "InvalidOperationException: Collection was modified". New elements should be gathered in a separate list or a new collection should be generated with LINQ.

Correct

var items = new List<int> { 1, 2, 3 };
items.AddRange(items.Select(item => item * 2).ToList());

Frequently asked questions

Should I use foreach or for?

If you only need the elements, use foreach: it is shorter, more readable, and you cannot make index errors. If you need an index, are traversing backward, or the step size is other than one, for is required.

Can I modify the collection inside a foreach?

No, it throws an error. Use RemoveAll to delete, or LINQ's Select method to transform. If you really need to modify inside the loop, traversing backward with a for loop is safe because deleted elements do not affect the remaining indices.

Is LINQ slower than a loop?

It brings a very small overhead, but in most applications, it is unmeasurable. The gain is in readability and reduced risk of errors. If you are writing a tight loop over millions of elements, it is wise to measure and decide.

Summary

In C#, foreach is the default way to traverse collections; for is used when an index is needed. Modifying the collection while traversing throws an error, and LINQ is a readable alternative to loops.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code