➕︎ Aa ➖︎ |Dark 1 ● Dark 2 ● Light|Hack ● Fira Code|Back to PT Mono✖
// CPCS-324 Algorithms and Data Structures 2
// 2-Dimensional array demo
// 2020, Dr. Muhammad Al-Hashimi
// for a 2-dim array declare and initialize array of 2 empty arrays
var a = [ [], [] ];
// use 2-dim array for 2x2 matrix where a[row][col]
a[0][0] = 5;
a[0][1] = 6;
a[1][0] = 7;
a[1][1] = 8;
// print the whole matrix
document.write("<p>", a, "</p>");
// print first row of matrix
document.write("<p>", a[0], "</p>");
// print second row of matrix
document.write("<p>", a[1], "</p>");
// it can grow as elements are added; be careful though!
// we can have as many columns as we want but only 2 rows
// add 3rd value to 2nd row; still 2-dim array but no longer 2x2 matrix
a[1][2] = 9;
document.write("<p>", a, "</p>");
// add 3rd value to 1st row
a[0][2] = 10;
document.write("<p>", a, "</p>"); // 3-col matrix (still 2 rows)
// the following will break the code; try it (check console tab)
//a[2][0] = 10; // can't add value to nonexistent third row (indexed 2)
// -----------------------------------------
// build n x m matrix in a 2-dimensional array
// declare an empty array; it will grow as rows are added
var b = [];
// add a dimension: for a 12-row matrix create 12 arrays inside b
for (var i=0; i < 12; i++)
{
b[i] = []; // b = [ [], [], ... ]
// use b[i][j] notation to add elements inside b[i],
// to get a 12x12 matrix, each b[i] must also have
// 12 elements
}
document.write("<p>", b, "</p>");
// -----------------------------------------
// matrices and tables are 2-dimensional structures,
// for n-dimensional stuff nest array declarations deeper
//