Start learning free

LESSON 108 OF 347 · FOR LOOPS - LOOPING OVER ARRAYS

For Loop Execution Flow in C#: foreach Over an Array

Lesson Read the full explanation

C# uses the brackets ({}) to indicate which lines of code are part of a for loop and which are not.

Take this code for example:

string[] languages = {"Python", "Java", "JavaScript"};

for (string language : languages) {
  Console.WriteLine("I love " + language);
  Console.WriteLine("I want to get better at it");
}

Both Console.WriteLine statements are part of the loop since they are written inside the brackets.

This means that both messages will be printed for every language in the languages list. The output of that code would be:

I love Python
I want to get better at it
I love Java
I want to get better at it
I love JavaScript
I want to get better at it

As for this code:

string[] languages = {"Python", "Java", "JavaScript"};

for (string language : languages) {
  Console.WriteLine("I love " + language);
}
Console.WriteLine("I want to get better at them");

The Console.WriteLine("I want to get better at them"); is not part of the loop.

This means that only Console.WriteLine("I love " + language); will be executed for every language in the languages list.

Then, when the for loop is over, the Console.WriteLine("I want to get better at them"); will be executed only once.

The output of this program would be:

I love Python
I love Java
I love JavaScript
I want to get better at them

Execution flow

Lastly, note that the execution of a program always begins on the first line. The code is then executed one line at a time from top to bottom. This is known as execution flow and is the order a program in C# executes code.

For example, this program:

string[] fruits = {"banana", "apple", "kiwi"};

Console.WriteLine("I'm hungry!");

for (string fruit : fruits) {
  Console.WriteLine("I'm gonna eat:");
  Console.WriteLine(fruit);
}
  

Console.WriteLine("I love my life!");

prints:

I'm hungry!
I'm gonna eat:
banana
I'm gonna eat:
apple
I'm gonna eat:
kiwi
I love my life!


Assignment:

Add a for loop inside our code in the editor such that the final program would print:

Today we'll learn about:
Python
Java
JavaScript
Let's code!
STEP 1 OF 1
    Ctrl + Enter to check

    C# · FOR LOOPS - LOOPING OVER ARRAYS

    Exercise Create A For Loop in C#, explained

    What this lesson covers

    Two ideas come together here. The first is which lines belong to a loop: in C#, the braces {} mark the loop body, and only the statements inside them repeat. The second is execution flow: a program starts at its first line and runs one statement at a time, top to bottom, and a loop sends the flow back up to repeat its body before moving on.

    The loop body and the braces

    When you want to visit every element of an array, C# uses foreach. The loop variable is declared in the header, followed by the keyword in and the array:

    string[] languages = {"Python", "Java", "JavaScript"};
    
    foreach (string language in languages) {
        Console.WriteLine("I love " + language);
        Console.WriteLine("I want to get better at it");
    }
    

    Both Console.WriteLine calls sit between the braces, so both run for every element. The output alternates between the two messages:

    I love Python
    I want to get better at it
    I love Java
    I want to get better at it
    I love JavaScript
    I want to get better at it
    

    Now move the second message below the closing brace:

    foreach (string language in languages) {
        Console.WriteLine("I love " + language);
    }
    Console.WriteLine("I want to get better at them");
    
    I love Python
    I love Java
    I love JavaScript
    I want to get better at them
    

    The last statement is no longer part of the loop. It runs once, after the loop has finished with the last element. The indentation doesn't decide this, the braces do. Indenting is a habit that makes the structure easy to see, and C# ignores it.

    The foreach syntax

    The header has three parts: the type of each element (string), a name for the loop variable (language), and the collection to walk through (languages). The word in separates the last two. On each pass the variable holds the next element, in order, from the first to the last. There is no index to manage.

    Code ported from Java often uses a colon instead, as in for (string language : languages). That form doesn't exist in C#, and the compiler rejects it. In C# the keyword is foreach and the separator is in.

    Execution flow

    Follow this program line by line:

    string[] fruits = {"banana", "mango", "cherry"};
    
    Console.WriteLine("I'm hungry!");
    
    foreach (string fruit in fruits) {
        Console.WriteLine("I'm gonna eat:");
        Console.WriteLine(fruit);
    }
    
    Console.WriteLine("I love my life!");
    

    The array is created, then I'm hungry! is printed once. The flow enters the loop and runs the body for banana, then goes back to the top of the loop for mango, and again for cherry. When the array has no more elements, the flow continues with the first statement after the closing brace.

    I'm hungry!
    I'm gonna eat:
    banana
    I'm gonna eat:
    mango
    I'm gonna eat:
    cherry
    I love my life!
    

    Statements before the loop run once, before it. The loop body runs once per element. Statements after the loop run once, after it.

    The exercise, step by step

    The editor has an array of three languages, a print statement that introduces the list, a comment marking the spot, and a closing print statement. The program should print:

    Today we'll learn about:
    Python
    Java
    JavaScript
    Let's code!
    
    1. Write the loop header between the two existing prints: foreach (string language in languages), with an opening brace.
    2. Print the loop variable inside the body with Console.WriteLine(language), so each language gets its own line.
    3. Close the brace before the last print. Let's code! must stay outside the loop, or it would be printed three times.
    string[] languages = {"Python", "Java", "JavaScript"};
    
    Console.WriteLine("Today we'll learn about:");
    
    // Write the for loop below:
    foreach (string language in languages) {
        Console.WriteLine(language);
    }
    
    Console.WriteLine("Let's code!");
    

    Common mistakes

    • A statement in the wrong place. Putting Let's code! inside the braces repeats it for each element. Putting the intro line inside has the same effect.
    • Using the loop variable after the loop. language exists only between the braces. Using it on a line after the closing brace gives a compile error, because that name isn't in scope there.
    • Assigning to the loop variable. language = "C#"; inside the body doesn't compile, because a foreach variable is read-only.

    Key takeaways

    • The braces decide which statements are part of the loop; indentation is only for readers.
    • foreach (Type name in collection) visits each element once, in order.
    • Programs run top to bottom; a loop repeats its body and then the flow moves on.
    • The loop variable is only available inside the loop body.
    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