Start learning free

LESSON 104 OF 347 · FOR LOOPS - LOOPING OVER ARRAYS

Why For Loops in C#: Repetition Without Copy and Paste

Lesson Read the full explanation

For loops are very useful for iterating over sequences of elements.

To understand the value of for loops, let’s take some time to see how frustrating our life would be if a repeated task required us to type out the same code every single time.


Example: Greeting our friends

Imagine this: We have an array of friends and we want to greet each of them using a message template.

If we only use Console.WriteLine(), our program might look like this:

string[] friends = {"Andy", "Mircea", "David", "Mary"};

Console.WriteLine("Hey, " + friends[0]);
Console.WriteLine("Hey, " + friends[1]);
Console.WriteLine("Hey, " + friends[2]);
Console.WriteLine("Hey, " + friends[3]);

That’s ugly, but still manageable. After all, we’re writing only 4 lines of code and most probably copying and pasting a few times.

Now imagine if we had 10, 100 friends? It would take an extremely long time and by the end, we could still end up with inconsistencies and mistakes.

We’ll learn how for loops come to our rescue in the next lesson. But for now, let’s gain an appreciation for them.


Assignment
Follow the Coding Tutorial to see how frustrating our life is without for loops.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    C# · FOR LOOPS - LOOPING OVER ARRAYS

    Why For Loops in C#, explained

    The problem loops solve

    Programs often repeat the same action for many values: greet every user, print every item, add up every price. Without a loop, you write one statement per value. This lesson makes you feel that cost first, so the loops in the next lesson make sense.

    Greeting friends the hard way

    Suppose there is an array of friends and you want to print a greeting for each:

    string[] friends = {"Andy", "Mircea", "David", "Mary"};
    
    Console.WriteLine("Hey, " + friends[0]);
    Console.WriteLine("Hey, " + friends[1]);
    Console.WriteLine("Hey, " + friends[2]);
    Console.WriteLine("Hey, " + friends[3]);
    

    For four friends that is tolerable. The statements are almost identical, and only the index changes. Now picture 100 friends, or a list whose size you don't know until the program runs. Writing one line per element has real problems:

    • It doesn't scale. Ten times the data means ten times the code.
    • It's error-prone. After pasting the line a hundred times, you can easily leave a wrong index in one of them.
    • It can't adapt. The code only works for an array of exactly this length. If the array has 3 items, friends[3] throws an IndexOutOfRangeException. If it has 5, the last one is silently skipped.
    • It's hard to change. To alter the greeting you edit every line, and missing one makes the output inconsistent.

    Arrays, indexes and Length

    The lesson reads elements by index, so a refresher helps. A C# array is zero-based: the first element is at index 0, and an array with 4 elements has indexes 0 to 3. The number of elements is the array's Length property, so the last valid index is always Length - 1.

    string[] fruits = {"banana", "orange", "pear", "kiwi"};
    
    Console.WriteLine(fruits[0]);       // banana
    Console.WriteLine(fruits[3]);       // kiwi
    Console.WriteLine(fruits.Length);   // 4
    

    Using + with a string and another string joins them. "I eat " + fruits[0] produces I eat banana. Console.WriteLine prints the result and moves to a new line.

    What the repetition tells you

    Whenever you notice code that repeats with one small change, there are two things to separate: the part that stays the same, which here is Console.WriteLine("Hey, " + ...), and the part that varies, which is the index. A loop is the tool for exactly this split. You write the fixed part once, and the loop supplies each value of the varying part in turn.

    The payoff is that the code no longer depends on how many items there are. The same loop works for 3 friends, 4 friends or 4,000. To change the greeting you edit one line. And because you never type the indexes yourself, you can't mistype one.

    The exercise, step by step

    The lesson gives you an array of four fruits and asks you to print I eat followed by each fruit, using only Console.WriteLine statements and no loop.

    1. Write one statement for the first fruit. Join "I eat " with fruits[0] using +, and pass the result to Console.WriteLine. Keep the space at the end of the text so the words don't run together.
    2. Repeat it with indexes 1, 2 and 3. That makes four statements in total, one per fruit and in array order.
    string[] fruits = {"banana", "orange", "pear", "kiwi"};
    
    Console.WriteLine("I eat " + fruits[0]);
    Console.WriteLine("I eat " + fruits[1]);
    Console.WriteLine("I eat " + fruits[2]);
    Console.WriteLine("I eat " + fruits[3]);
    

    The output is:

    I eat banana
    I eat orange
    I eat pear
    I eat kiwi
    

    Look at the four lines. Only the number inside the brackets changes. A for loop lets you write the repeated part once and have the computer supply the changing part.

    Common mistakes

    • Starting at index 1. Arrays start at 0, so fruits[1] is the second fruit.
    • Going past the end. fruits[4] doesn't exist in a four-element array and throws an IndexOutOfRangeException at run time.
    • Dropping the space in the text. "I eat" + fruits[0] prints I eatbanana.
    • Writing the fruit names into the text. The statements should read from the array, not copy the names, so a change to the array shows up in the output.

    Key takeaways

    • Writing the same statement once per element doesn't scale, and it breaks when the data changes size.
    • Arrays are zero-based: valid indexes run from 0 to Length - 1.
    • When only an index changes between statements, a loop can do the repeating for you.
    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