Programming Fundamentals/Arrays/JavaScript

arrays.js

edit
// This program uses arrays to display temperature conversion tables 
// and temperature as an array subscript to find a given conversion.
//
// References:
//   https://www.mathsisfun.com/temperature-conversion.html
//   https://en.wikibooks.org/wiki/JavaScript

main();

function main() 
{
    var c;
    var f;
    
    c = buildC(100);
    f = buildF(212);
    displayArray("C", c);
    displayArray("F", f);
    findTemperature(c, f);
}

function buildC(size) 
{
    var c = [];
    var index;
    var value;
    
    for (index = 0 ; index <= size; index += 1) 
    {
        value = index * 9 / 5 + 32; 
        c.push(value);
    }
    
    return c;
}

function buildF(size) 
{
    var f = [];
    var index;
    var value;
    
    for (index = 0 ; index <= size; index += 1) 
    {
        value = (index - 32) * 5 / 9; 
        f.push(value);
    }
    
    return f;
}

function displayArray(name, array) 
{
    var index;
    
    for (index = 0 ; index <= array.length - 1 ; index += 1) 
    {
        output(name + "[" + index + "] = " + array[index]);
    }
}

function findTemperature(c, f) 
{
    var temp;
    var size;
    
    size = minimum(c.length, f.length);
    do 
    {
        temp = input("Enter a temperature between 0 and " + (size - 1));
    } while (temp < 0 || temp > size - 1);
    output(temp + "° Celsius is " + c[temp] + "° Fahrenheit");
    output(temp + "° Fahrenheit is " + f[temp] + "° Celsius");
}

function minimum(value1, value2) 
{
    var result;
    
    if (value1 < value2) 
    {
        result = value1;
    }
    else
    {
        result = value2;
    }
    
    return result;
}

function input(text) {
  if (typeof window === 'object') {
    return prompt(text)
  }
  else if (typeof console === 'object') {
    const rls = require('readline-sync');
    var value = rls.question(text);
    return value;
  }
  else {
    output(text);
    var isr = new java.io.InputStreamReader(java.lang.System.in); 
    var br = new java.io.BufferedReader(isr); 
    var line = br.readLine();
    return line.trim();
  }
}

function output(text) {
  if (typeof document === 'object') {
    document.write(text);
  } 
  else if (typeof console === 'object') {
    console.log(text);
  } 
  else {
    print(text);
  }
}

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own JavaScript compiler / interpreter / IDE.

See Also

edit