Search code examples
c#arraysforeachconsole.readline

Looping values into a two-dimensional array with a foreach loop?


So I'm trying to loop values into a two-dimensional array using foreach. I know the code should look something like this.

        int calc = 0;
        int[,] userfields = new int[3,3];

        foreach (int userinput in userfields)
        {

            Console.Write("Number {0}: ", calc);
            calc++;
            userfields[] = Convert.ToInt32(Console.ReadLine());
        }

This is as far as I can get. I tried using

userfields[calc,0] = Convert.ToInt32(Console.ReadLine());

but apparently that doesn't work with two-dimensional arrays. I'm relatively new with C# and I'm trying to learn, so I appreciate all of the answers.

Thanks in advance!


Solution

  • It is a two dimensional array as the name suggests it has two dimensions. So you need to specify two index when you want to assign a value. Like:

    // set second column of first row to value 2
    userfield[0,1] = 2; 
    

    In this case probably you want a for loop:

    for(int i = 0; i < userfield.GetLength(0); i++)
    {
        for(int j = 0; j < userfield.GetLength(1); j++)
        {
           //TODO: validate the user input before parsing the integer
           userfields[i,j] = Convert.ToInt32(Console.ReadLine());
        }
    }
    

    For more information have a look at: