// This program demonstrates array processing, including:
// display, total, max, min, parallel arrays, sort,
// fixed arrays, dynamic arrays, and multidimensional arrays.
main()
function main() {
var names = ['Lisa', 'Michael', 'Ashley', 'Jacob', 'Emily'];
var ages = [49, 48, 26, 19, 16];
displayArray(names);
displayArray(ages);
var total = sum(ages);
var maximum = max(ages);
var minimum = min(ages);
output('total: ' + total);
output('maximum: ' + maximum);
output('minimum: ' + minimum);
displayParallel(names, ages);
ages.sort();
displayArray(ages);
fixedArray();
dynamicArray();
displayMultidimensional();
}
function displayArray(array) {
for (var index = 0; index < array.length; index++) {
output('array[' + index + '] = ' + array[index]);
}
}
function sum(array) {
var total = 0;
for (var index = 0; index < array.length; index++) {
total += array[index];
}
return total;
}
function max(array) {
var maximum = array[0];
for (var index = 1; index < array.length; index++) {
if (maximum < array[index]) {
maximum = array[index];
}
}
return maximum;
}
function min(array) {
var minimum = array[0];
for (var index = 1; index array[index]) {
minimum = array[index];
}
}
return minimum;
}
function displayParallel(names, ages) {
for (var index = 0; index < names.length; index++) {
output(names[index] + ' is ' + ages[index] + ' years old');
}
}
function fixedArray() {
var array = new Array(5);
for (var index = 0; index < array.length; index++) {
var number = Math.floor(Math.random() * 100);
array[index] = number;
}
displayArray(array);
}
function dynamicArray() {
var array = [];
for (var index = 0; index < 5; index++) {
var number = Math.floor(Math.random() * 100);
array.push(number);
}
displayArray(array);
}
function displayMultidimensional() {
var game = [
['X', 'O', 'X'],
['O', 'O', 'O'],
['X', 'O', 'X'] ];
for (var row = 0; row < 3; row++) {
var line = '';
for (var column = 0; column < 3; column++) {
line += game[row][column];
if (column < 2) {
line += ' | ';
}
}
output(line);
}
}
function output(text) {
if (typeof document === 'object') {
document.write(text);
}
else if (typeof console === 'object') {
console.log(text);
}
else {
print(text);
}
}