# Running arr2dim_demo.js

➕︎ Aa ➖︎ |Dark 1Dark 2Light|HackInput Mono|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 = 5;
a = 6;
a = 7;
a = 8;

// print the whole matrix
document.write("<p>", a, "</p>");

// print first row of matrix
document.write("<p>", a, "</p>");

// print second row of matrix
document.write("<p>", a, "</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 = 9;
document.write("<p>", a, "</p>");

// add 3rd value to 1st row
a = 10;
document.write("<p>", a, "</p>");  // 3-col matrix (still 2 rows)

// the following will break the code; try it (check console tab)
//a = 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
//
``````