We can create multidimensional arrays by creating arrays of arrays.
With that information, we can create a two-dimensional array with n rows and one column:
var twod = [];
var rows = 5;
for (var i = 0; i < rows; ++i) {
twod[i] = [];
}
var grades = [[98, 79, 72],[96, 92, 91],[81, 84, 89]];
var total = 0;
var average = 0.0;
for (var row = 0; row < grades.length; ++row) {
for (var col = 0; col < grades[row].length; ++col) {
total += grades[row][col]; /* www .ja v a 2 s. com*/
}
average = total / grades[row].length;
console.log("Student " + parseInt(row+1) + " average: " + average.toFixed(2));
total = 0;
average = 0.0;
}
The code above generates the following result.
To perform a row-wise computation, flip the for loops so that the outer loop controls the columns and the inner loop controls the rows.
Here is the calculation for each test:
var grades = [[89, 77, 78],[76, 82, 81],[91, 94, 89]];
var total = 0;
var average = 0.0;
for (var col = 0; col < grades.length; ++col) {
for (var row = 0; row < grades[col].length; ++row) {
total += grades[row][col]; /*from w w w .ja v a 2 s . c o m*/
}
average = total / grades[col].length;
console.log("Test " + parseInt(col+1) + " average: " + average.toFixed(2));
total = 0;
average = 0.0;
}
The code above generates the following result.
A jagged array is an array where the rows in the array may have a different number of elements.
var grades = [[99, 97],[96, 92, 81],[81, 84, 89, 89]];
var total = 0;
var average = 0.0;
for (var row = 0; row < grades.length; ++row) {
for (var col = 0; col < grades[row].length; ++col) {
total += grades[row][col]; /*from w w w . ja v a2 s . c o m*/
}
average = total / grades[row].length;
console.log("Student " + parseInt(row+1) + " average: " + average.toFixed(2));
total = 0;
average = 0.0;
}
The code above generates the following result.