- Write
for,whileanddo-whileloops and control them withbreakandcontinue - 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++).
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"7 x {i} = {7 * i}");
}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?
int savings = 100;
int months = 0;
while (savings < 150)
{
savings += 20;
months++;
}
Console.WriteLine($"After {months} months: {savings} AZN");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.
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}");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.
break stops the loop immediately, while continue skips the rest of the current step and moves on to the next one:
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");
}4 is even 10 is even Negative number, stop.
`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.
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"));3 Lankaran, Baku, Shaki True 2
Add(x)adds an element to the end,Insert(i, x)at positioni.Remove(x)removes a value,RemoveAt(i)removes the element at indexi.Contains(x)tells whether an element is there, andIndexOf(x)gives its index (or-1if 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.
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");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.
| Collection | When to use it | Example |
|---|---|---|
T[] | the number of elements is fixed | the 7 days of the week |
List<T> | elements are added and removed | a shopping basket |
Dictionary<TKey,TValue> | values must be found quickly by key | city → population |
Key points
forrepeats a known number of times,whilerepeats while a condition is true;do-whileruns at least once.breakstops the loop,continuejumps to the next step.- An array has a fixed size and indexes start at 0;
foreachvisits every element. - A
List<T>can grow and shrink:Add,Remove,Count. - A
Dictionary<TKey,TValue>stores values by key;TryGetValueis the safe lookup.
Check yourself
10 questions. Every correct answer earns XP.
for (int i = 0; i < 3; i++) repeat?