Start learning free

LESSON 106 OF 347 · FOR LOOPS - LOOPING OVER ARRAYS

Looping Over Arrays in C#: Fixing the Buggy foreach

Practice Read the full explanation

Inside the code editor we've tried to write a for loop that greets every student in the students array.

So when we ran the code, we expected it to print:

Welcome, Andy
Welcome, Sally
Welcome, John

but it seems like we made some mistakes because when we run our code, it produces errors.


Assignment:

Your task is to fix our loop such that no errors will be produced and it will print the desired output.

STEP 1 OF 1
    Ctrl + Enter to check

    C# · FOR LOOPS - LOOPING OVER ARRAYS

    Buggy Code For Loops 1 in C#, explained

    What the code is supposed to do

    The program has an array of three students and should greet each one on its own line:

    Welcome, Andy
    Welcome, Sally
    Welcome, John
    

    The starting code is:

    string[] students = {"Andy", "Sally", "John"};
    
    foreach (string name in students) {
    }
    Console.WriteLine("Welcome, " + student);
    

    It doesn't compile, so nothing is printed. There are two separate mistakes, and both have to be fixed.

    Bug 1: the name does not exist

    The loop header declares a loop variable called name. The print statement then uses a variable called student. No variable has that name, so the compiler stops with an error like The name 'student' does not exist in the current context. C# is strict about names: it matches them letter by letter, including case, and it never guesses what you meant.

    Notice that the array is called students (plural), the loop variable is name, and the message uses student (singular). Each is a different identifier. Names in the header and the body need to agree.

    Bug 2: the print is outside the loop

    The loop has braces, but there is nothing between them. The body of a foreach is only what sits between its { and }, so the loop currently does nothing on each pass. The Console.WriteLine comes after the closing brace. It is an ordinary statement that runs once, after the loop is over.

    Even with the name problem fixed, this layout would not produce the expected output. At that point the loop variable isn't in scope any more: a variable declared in the foreach header exists only inside the loop. So the print statement can't use it there, and moving the statement into the body is not just a matter of style.

    Fixing it step by step

    1. Pick one name for the loop variable. Either name works if you use it consistently. The reference solution calls it student, which reads well in a loop over students, so rename the variable in the header.
    2. Move the print statement inside the braces. Then it runs once per element, with the loop variable holding the current student.
    3. Check the text. The message is "Welcome, " with a space after the comma, followed by the student's name. Console.WriteLine ends each line.

    The fixed code in C#

    string[] students = {"Andy", "Sally", "John"};
    
    foreach (string student in students) {
        Console.WriteLine("Welcome, " + student);
    }
    

    Keeping the original name name and writing "Welcome, " + name in the body is equally correct. Both versions print the same three lines.

    Some details of the corrected code:

    • Each pass has its own value. On the first pass student holds "Andy", on the second "Sally" and on the third "John". The loop ends after the third.
    • Use in in the header. The C# form is foreach (string student in students). Code from other languages sometimes uses a colon, which doesn't compile here.
    • String joining. The + operator joins the text and the name. Console.WriteLine then prints the result and moves to the next line.
    • Braces mark the body. Indentation helps people read code but means nothing to the compiler. Only the braces decide which statements repeat.

    Common mistakes

    • Fixing only one of the two bugs. If you rename the variable but leave the print outside the loop, the code won't compile. If you move the print inside but leave the mismatch, the same error remains.
    • Putting the print inside the braces but using the array name. "Welcome, " + students compiles, since any object can be joined to text, but it prints the array's type name instead of a person. The body has to use the loop variable.
    • Adding the greeting in a second loop or copying it three times. The point of the loop is to write it once.
    • Changing the array. The array contents are right as they are.

    Checking your fix

    Run the code. A correct fix compiles and prints exactly the three lines above, in the order of the array. Try adding a fourth name to the array: with the loop written correctly, a fourth greeting appears without any other change.

    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