Skip to content
Educora
Beginner22 min4 / 16

Loops, arrays and collections

Repeat work with `for`, `while` and `foreach` loops and store data in arrays, `List<T>` and `Dictionary<TKey,TValue>`.

Check yourself
In this lesson you will learn
  • Write for, while and do-while loops and control them with break and continue
  • Create an array and go through its elements with foreach
  • Add elements to and remove them from a List<T>
  • Store and look up values by key in a Dictionary<TKey,TValue>

To print the 7 times table you could write ten Console.WriteLine lines. But what if you needed 1000 lines? In programming, repeated work is done by loops. Loops usually go hand in hand with collections — arrays, lists and dictionaries that keep many values in one place: the scores of every student in a class, the items in a basket, the products in a warehouse.

for and while loops

A for loop is handy when you know the number of steps in advance. Its header has three parts separated by semicolons: the counter's starting value (int i = 1), the condition to keep going (i <= 5) and the change after each step (i++).

C#
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"7 x {i} = {7 * i}");
}
Expected output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

A while loop repeats as long as its condition is true — it is used when the number of steps is not known in advance. For example, Elvin has 100 manat in his money box and adds 20 manat every month. After how many months will he reach 150 manat?

C#
int savings = 100;
int months = 0;

while (savings < 150)
{
    savings += 20;
    months++;
}

Console.WriteLine($"After {months} months: {savings} AZN");
Expected output
After 3 months: 160 AZN

Arrays and foreach

An array is a fixed-size sequence of values of the same type. You can create one by listing the values in square brackets. Elements are accessed by index: the first element is [0] and the last is [^1]. The easiest way to go through all the elements of an array is a foreach loop.

C#
int[] scores = [90, 75, 88, 62];

Console.WriteLine(scores[0]);
Console.WriteLine(scores[^1]);
Console.WriteLine(scores.Length);

scores[3] = 70;

int sum = 0;
foreach (int s in scores)
{
    sum += s;
}
Console.WriteLine($"Sum: {sum}, average: {sum / scores.Length}");
Expected output
90
62
4
Sum: 323, average: 80

[90, 75, 88, 62] is a collection expression, added in C# 12. In older code the same array is written as new int[] { 90, 75, 88, 62 }, and new int[5] creates an array of five zeros. An array's size cannot change after it is created.

Interactive
Loading simulation…
Linear search: a loop checks the array's elements one by one and stops when it finds the target.

break stops the loop immediately, while continue skips the rest of the current step and moves on to the next one:

C#
int[] numbers = [4, 7, 10, -1, 12];

foreach (int n in numbers)
{
    if (n < 0)
    {
        Console.WriteLine("Negative number, stop.");
        break;
    }
    if (n % 2 != 0)
        continue;
    Console.WriteLine($"{n} is even");
}
Expected output
4 is even
10 is even
Negative number, stop.
7 was skipped because it is odd, and 12 was never reached.

`List<T>`: a growing list

When the number of elements will change, use a List<T> instead of an array. The T in angle brackets is the element type: List<string> is a list of strings, List<int> a list of numbers. Such types are called generic types. The Count property tells you how many elements there are.

C#
List<string> cities = ["Baku", "Ganja"];

cities.Add("Shaki");
cities.Insert(0, "Lankaran");
cities.Remove("Ganja");

Console.WriteLine(cities.Count);
Console.WriteLine(string.Join(", ", cities));
Console.WriteLine(cities.Contains("Baku"));
Console.WriteLine(cities.IndexOf("Shaki"));
Expected output
3
Lankaran, Baku, Shaki
True
2
  • Add(x) adds an element to the end, Insert(i, x) at position i.
  • Remove(x) removes a value, RemoveAt(i) removes the element at index i.
  • Contains(x) tells whether an element is there, and IndexOf(x) gives its index (or -1 if it is missing).
  • string.Join(", ", cities) joins all the elements into one string.

`Dictionary<TKey,TValue>`: keys and values

A dictionary stores every value under a unique key — like the names and numbers in a phone book. Dictionary<string, int> is a dictionary with string keys and int values. You reach a value by its key: stock["apples"]. Reading a key that does not exist throws a KeyNotFoundException, so TryGetValue is used for a safe check.

C#
Dictionary<string, int> stock = new()
{
    ["apples"] = 40,
    ["pears"] = 15
};

stock["plums"] = 25;
stock["apples"] -= 5;

foreach (var (fruit, amount) in stock)
{
    Console.WriteLine($"{fruit}: {amount}");
}

if (stock.TryGetValue("kiwi", out int kiwis))
    Console.WriteLine($"Kiwi: {kiwis}");
else
    Console.WriteLine("No kiwi in stock");
Expected output
apples: 35
pears: 15
plums: 25
No kiwi in stock

foreach (var (fruit, amount) in stock) splits every pair into its key and value. TryGetValue returns true when the key is found and writes the value into the variable passed with out — we will look at out in detail in the methods lesson.

CollectionWhen to use itExample
T[]the number of elements is fixedthe 7 days of the week
List<T>elements are added and removeda shopping basket
Dictionary<TKey,TValue>values must be found quickly by keycity → population

Key points

  • for repeats a known number of times, while repeats while a condition is true; do-while runs at least once.
  • break stops the loop, continue jumps to the next step.
  • An array has a fixed size and indexes start at 0; foreach visits every element.
  • A List<T> can grow and shrink: Add, Remove, Count.
  • A Dictionary<TKey,TValue> stores values by key; TryGetValue is the safe lookup.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
How many times does for (int i = 0; i < 3; i++) repeat?