What index-based looping is
A foreach loop hands you the values of an array one by one. Sometimes the value alone isn't enough, and you also need to know where it sits: to print a position, to compare an element with its neighbour, to change an element, or to return an index. For those jobs you loop over the indices and use each one to reach into the array.
Array indices in C# start at 0. An array with Length elements has the valid indices 0 through Length - 1. The array {"pancakes", "pasta", "pizza", "avocado"} has four elements, so its indices are 0, 1, 2 and 3.
The syntax
The standard pattern is a for loop with an index variable, usually named i:
string[] meals = {"pancakes", "pasta", "pizza", "avocado"};
for (int i = 0; i < meals.Length; i++) {
Console.WriteLine("Meal number " + (i + 1) + " is " + meals[i] + ".");
}
It prints:
Meal number 1 is pancakes.
Meal number 2 is pasta.
Meal number 3 is pizza.
Meal number 4 is avocado.
The header has three parts, separated by semicolons:
int i = 0starts at the first index. It runs once, before the loop.i < meals.Lengthis checked before every pass. The loop stops as soon as it is false. With four meals,iruns through 0, 1, 2, 3, and the loop ends whenireaches 4.i++adds 1 toiafter every pass.
Inside the loop, meals[i] is the element at the current position, and i itself is the position.
Length is a property
The number of elements of a C# array is Length, with a capital L and no parentheses. It is a property, not a method. Code from other languages often has length, length() or size(), and none of them compile for a C# array.
Why the day is i + 1
Indices start at 0, but people count from 1. To print "day 1" for the first element, the text uses i + 1. The parentheses matter. With + and a string, C# evaluates left to right, and once a string is on the left, a number joins as text:
Console.WriteLine("Meal number " + 1 + 1); // Meal number 11
Console.WriteLine("Meal number " + (1 + 1)); // Meal number 2
String interpolation is a tidier way to write the same message: $"Meal number {i + 1} is {meals[i]}." needs no parentheses and gives the same text.
When to use indices instead of foreach
- You need the position, as in "On day 3 ..." or returning the index of a match.
- You compare neighbours, using
nums[i]andnums[i + 1]. The loop must then stop one element early:i < nums.Length - 1. - You change elements. Writing
nums[i] = nums[i] * 2updates the array. Aforeachvariable is only a copy of each element and can't be assigned to. - You go backwards or skip elements.
for (int i = nums.Length - 1; i >= 0; i--)walks from the end, andi += 2visits every second element.
When none of these applies, foreach is shorter and can't go out of range.
Common mistakes and gotchas
- Using
<=instead of<. Withi <= meals.Lengththe last pass readsmeals[4], which doesn't exist. C# checks every array access, so the program stops with anIndexOutOfRangeExceptioninstead of reading unrelated memory. - Starting at 1. The first element is silently skipped, with no error at all.
- Writing
Length - 1in the condition.i < Length - 1misses the last element. It is correct only when you also readnums[i + 1]. - Empty arrays. With
Lengthequal to 0, the condition0 < 0is false at once and the loop body never runs, which is the behaviour you want. - Forgetting the parentheses around
i + 1. The output turns into "day 01" instead of "day 1", because the numbers are joined as text.
The exercise, step by step
The lesson gives you the array int[] temperatures = {10, 60, -5, 32}; and asks you to print one line per day.
- Write a
forloop over the indices. Useint i = 0, the conditioni < temperatures.Lengthandi++. The condition uses the array'sLength, so the loop adapts if the array changes. - Print one line per pass. Inside the loop, call
Console.WriteLinewith the text"On day " + (i + 1) + " the temperature is " + temperatures[i] + ".". The day isi + 1because days start at 1, and the temperature istemperatures[i].
int[] temperatures = {10, 60, -5, 32};
for (int i = 0; i < temperatures.Length; i++) {
Console.WriteLine("On day " + (i + 1) + " the temperature is " + temperatures[i] + ".");
}
The output is:
On day 1 the temperature is 10.
On day 2 the temperature is 60.
On day 3 the temperature is -5.
On day 4 the temperature is 32.
Key takeaways
- Valid indices of an array run from
0toLength - 1. - The loop
for (int i = 0; i < arr.Length; i++)visits every element, andarr[i]is the element at positioni. Lengthis a property of arrays: capital L, no parentheses.- Put parentheses around
i + 1when it is joined to a string, or use string interpolation. - Reach for an index loop when you need the position, a neighbour, a change to the array, or a reverse walk. Otherwise
foreachis simpler.