It looks like you might be getting an error because of a syntax or structural issue with your code, possibly related to how you've written the loop or the code blocks. Based on your description, it seems like you're on the right track but maybe there’s some confusion with how the curly braces {}
are being used or maybe an accidental code placement outside of the method scope.
Original Code:
string[] personNamn = new string[3];
personNamn[0] = "Adam";
personNamn[1] = "Bertil";
personNamn[2] = "Ceasar";
for (int i = 0; i < 3; i++)
{
Console.WriteLine(personNamn[i]);
}
The error message you're receiving might happen if there is a misplacement of curly braces or if something outside the scope of the loop is incorrectly structured. Double-check if your method or class is correctly formatted around the code.
- Try placing the
for
loop and array declaration are inside a method, likeMain()
using System;
class Program
{
static void Main(string[] args)
{
string[] personNamn = new string[3];
personNamn[0] = "Adam";
personNamn[1] = "Bertil";
personNamn[2] = "Ceasar";
for (int i = 0; i < 3; i++)
{
Console.WriteLine(personNamn[i]);
}
}
}
- Ensure that each opening
{
has a corresponding closing}
. - The array initialization part you’ve written is fine for assigning values manually. However, if you want to make it more compact, you could also initialize it like this:
string[] personNamn = { "Adam", "Bertil", "Ceasar" };
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin