Start learning free

LESSON 144 OF 347 · LOOPING OVER ARRAY INDICES

Looping Through Arrays With Indices in C#

Lesson Read the full explanation

In some instances, we will want to loop through an array using indices.

The indices of an array meals are all the integer values from 0 to meals.length - 1, so we can iterate over them using an index variable i:

string[] meals = {"pancakes", "pasta", "pizza", "avocado"};

for (int i = 0; i < meals.length; i++) {
	Console.WriteLine("Meal number " + (i + 1) + " is " + meals[i] + ".");
}

The output of this code is:

Meal number 1 is pancakes.
Meal number 2 is pasta.
Meal number 3 is pizza.
Meal number 4 is avocado.

Assignment
Now let's print the temperature on each day, in this format:

On day 1 the temperature is 10.

On day 2 the temperature is 60.

...


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    C# · LOOPING OVER ARRAY INDICES

    Looping Through Arrays With Indices in C#, explained

    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 = 0 starts at the first index. It runs once, before the loop.
    • i < meals.Length is checked before every pass. The loop stops as soon as it is false. With four meals, i runs through 0, 1, 2, 3, and the loop ends when i reaches 4.
    • i++ adds 1 to i after 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] and nums[i + 1]. The loop must then stop one element early: i < nums.Length - 1.
    • You change elements. Writing nums[i] = nums[i] * 2 updates the array. A foreach variable 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, and i += 2 visits 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 <. With i <= meals.Length the last pass reads meals[4], which doesn't exist. C# checks every array access, so the program stops with an IndexOutOfRangeException instead of reading unrelated memory.
    • Starting at 1. The first element is silently skipped, with no error at all.
    • Writing Length - 1 in the condition. i < Length - 1 misses the last element. It is correct only when you also read nums[i + 1].
    • Empty arrays. With Length equal to 0, the condition 0 < 0 is 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.

    1. Write a for loop over the indices. Use int i = 0, the condition i < temperatures.Length and i++. The condition uses the array's Length, so the loop adapts if the array changes.
    2. Print one line per pass. Inside the loop, call Console.WriteLine with the text "On day " + (i + 1) + " the temperature is " + temperatures[i] + ".". The day is i + 1 because days start at 1, and the temperature is temperatures[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 0 to Length - 1.
    • The loop for (int i = 0; i < arr.Length; i++) visits every element, and arr[i] is the element at position i.
    • Length is a property of arrays: capital L, no parentheses.
    • Put parentheses around i + 1 when 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 foreach is simpler.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free