-2

i have array that call nums, it contain int var. the array is 2d -

int[,] nums = new int[lines, row];

i need to print each line in the array in other line.

when i try to print to array like this:

 for (int i = 0; i < lines; i++)
            for (int j = 0; j < 46; j++)
                Console.Write(nums[i,j]);

** when i using the above syntax i dont get an error in visual studio, but when i run the program, i got error in this line - Console.Write(nums[i,j]);.

error - system.IndeOutOfRangeException.

i got the error , i try to change the syntax to this:

 for (int i = 0; i < lines; i++)
            for (int j = 0; j < 46; j++)
                Console.Write(nums[i][j]);

the error: "wrong number of indices inside []; expected 2"

and:

 for (int i = 0; i < lines; i++)
            for (int j = 0; j < 46; j++)
                Console.Write(nums[i][j].tostring());

update

i am so stupid... i write 46(number in my program) instead of 6(numbers in each row) thats whey is was out of range.

ty for all, and i am sry to open a question with such bad problem...

TY!

doron hine
  • 13
  • 7

2 Answers2

1

If lines and row are positive integer values, say, int lines = 5; int row = 7; you can print out your table like this:

  int[,] nums = new int[lines, row]; // <- Multidimensional (2 in this case) array, not an array of array which is nums[][]

  //TODO: fill nums with values, otherwise nums will be all zeros

  for (int i = 0; i < lines; i++) {
    Console.WriteLine(); // <- let's start each array's line with a new line

    for (int j = 0; j < row; j++) { // <- What the magic number "46" is? "row" should be here... 
      Console.Write(nums[i, j]); // <- nums[i, j].ToString() doesn't spoil the output

      if (j > 0) // <- let's separate values by spaces "1 2 3 4" instead of "1234"
        Console.Write(" ");
    }
  }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • @doron hine: Try to avoid magic numbers like 6 or 46: what "6" stands for? Put "row" instead, or compute a value: "nums.GetLength(1)" – Dmitry Bychenko Aug 20 '13 at 10:43
0

You are dealing with 2 different types of arrays

int[,] nums = new int[lines, row];

is a Multi-Dimensional Array. Elements of the array can be accessed using nums[x,y].

When you use nums[x][y] you are dealing with an array of arrays.

You cannot use array of arrays syntax with a multi-dimensional array.

You might try What are the differences between Multidimensional array and Array of Arrays in C#? for details.

Community
  • 1
  • 1
AlanT
  • 3,627
  • 20
  • 28