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 anIndexOutOfRangeException. 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.
- Write one statement for the first fruit. Join
"I eat "withfruits[0]using+, and pass the result toConsole.WriteLine. Keep the space at the end of the text so the words don't run together. - 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 anIndexOutOfRangeExceptionat run time. - Dropping the space in the text.
"I eat" + fruits[0]printsI 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.