Giving each item in my 2d, dynamically sized by user input array an incrementing integer

Viewed 56

My code is supposed to take a user input, use that to determine the size of a 2d array, then turn the items in the array into incrementing integers from 0 onwards eg 0, 1, 2, 3, 4. This is the code I used:

    int userInput = int.Parse(Console.ReadLine());
        int[,] GridArray = new int[userInput, userInput];

        int k = 0;

        for (int i = 0; i < GridArray.Length; i++)
        {                    
            if (i == GridArray.GetLength(0))
            {
                k++;
            }
            int gridNumber = i + (k * GridArray.GetLength(0));
            Console.Write(gridNumber + " ");
        }

But the output from an input of 4 is like this: 0 1 2 3 8 9 10 11 12 13 14 15 16 17 18 19 Both a fix for my code and a method for doing what I am attempting easier would be greatly appreciated.

1 Answers

If I understand you correctly, when you enter 4 you would expect to see 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 as the output.

The way you have your nested loops set up, you will always have a never-ending inner loop. Variable 'k' only increments when 'i' is equal to the length of the zero dimension of your array; which is equal to the userinput. Which in the first iteration of the outer loop will NEVER occur. Variable 'i' equals zero for the entire first iteration through the inner loop.

What I believe you will want is to increment each variable within their respective loops. You will then take the inner loop's index, variable 'k' in your code, and add it to the outer loop's index multipled by the length of the inner loops count.

Try this, I've added the array position in the output for clarity:

        int userInput = int.Parse(Console.ReadLine());
        int[,] GridArray = new int[userInput, userInput];

        for (int i = 0; i < GridArray.GetLength(0); i++)
        {
            for (int k = 0; k < GridArray.GetLength(1);k++)
            { 
                int gridNumber = i* GridArray.GetLength(1) + k;
                Console.WriteLine("[{0},{1}] = {2}",i,k, gridNumber);
            }
        }
Related