Question

I am learning about multiple dimensional arrays, i have an understanding about how multiple dimensional arrays work and how to use them except for one thing, In what situation would we need to use these? and why?

Was it helpful?

Solution

Basically multi dimension arrays are used if you want to put arrays inside an array.

Say you got 10 students and each writes 3 tests. You can create an array like: arr_name[10][3]

So, calling arr_name[0][0] gives you the result of student 1 on lesson 1. Calling arr_name[5][2] gives you the result of student 6 on test 3.

You can do this with a 30 position array, but the multi dimension is:

1) easier to understand

2) easier to debug.

OTHER TIPS

Here are a couple examples of arrays in familiar situations.

  1. You might imagine a 2 dimensional array is as a grid. So naturally it is useful when you're dealing with graphics. You might get a pixel from the screen by saying

    pixel = screen[20][5]  // get the pixel at the 20th row, 5th column
    

    That could also be done with a 3 dimensional array to represent 3d space.

  2. An array could act like a spreadsheet. Here the rows are customers, and the columns are name, email, and date of birth.

    name = customers[0][0]
    email = customers[0][1]
    dateofbirth = customers[0][2]
    

Really there is a more fundamental pattern underlying this. Things have things have things... and so on. And in a sense you're right to wonder whether you need multidimensional arrays, because there are other ways to represent that same pattern. It's just there for convenience. You could alternatively

  1. Have a single dimensional array and do some math to make it act multidimensional. If you indexed pixels one by one left to right top to bottom you would end up with a million or so elements. Divide by the width of the screen to get the row. The remainder is the column.

  2. Use objects. Instead of using a multidimensional array in example 2 you could have a single dimensional array of Customer objects. Each Customer object would have the attributes name, email and dob.

So there's rarely one way to do something. Just choose the most clear way. With arrays you're accessing by number, with objects you're accessing by name.

Such solution comes as intuitive when you are faced with accessing a data element identified by a multidimensional vector. So if "which element" is defined by more than two "dimensions".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top