29) 2D Arrays¶
2D Arrays are a form of matrix. Just like arrays you can think of them as an array of arrays.
If 10 students have marks of Maths then you’d just declare an array of size 10 to store all those marks. But what if there were more subjects?
1D Arrays are just a single row or single column. 2D Arrays are like a grid. You can have both rows and columns. That’s not how they’re stored in memory, but we can understand them easily this way.
int programming[10];
int maths[10];
int physics[10];
int english[10];
programming is one array. maths is also one array. english and physics are also one array. But what if there were more subjects, maybe even hundreds or thousands? Instead of having to type out that many arrays, we just use a single 2D Array instead.int subjects[4][10];
Here we’ve declared a 2D Array called subjects. You could also call it marks, it doesn’t really matter. In the example above this one, you’d access the array by typing things like
programming[3] or maths[0]. Here, just replace those names with the Row index of the 2D Array. So if we say programming, maths, physics, english are the 4 rows of subjects[4][10], then subjects[0] is programming, subjects[1] is maths, subjects[2] is physics, and subjects[3] is english. And if I want to access programming[3], then I’d just type subjects[0][3], and if I want to access maths[0], then I’d write subjects[1][0].2D Arrays are usually handled via Nested loops. The outer loop deals with rows, and the inner loop deals with individual values (or columns) of each row.
1 2 3 4 5 6 7 | |
This code lets you access individual elements of the 2D array. But this would give garbage values as this array wasn’t initailized. Initialization is similar to a 1D Array but becomes a bit more specific. The declaration should also be looked at carefully. For example:
1 2 3 4 | |
The above isn’t something I understand, but I’ve been told by multiple teachers and really intelligent students that even though Compilers may sometimes work, the proper practice is the Correct declaration. As for Initialization:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
2D arrays have many uses in programming. You can implement hashtables and databases and much more in programming using them.