Jump to content

Programming Fundamentals/Loops/JavaScript

From Wikiversity

loops.js

[edit | edit source]
// This program demonstrates While, Do, and For loop counting using 
// user-designated start, stop, and increment values.
//
// References:
//   https://en.wikibooks.org/wiki/JavaScript

main()

function main() {
    var start = getValue("starting");
    var stop = getValue("ending");
    var increment = getValue("increment");

    whileLoop(start, stop, increment);
    doLoop(start, stop, increment);
    forLoop(start, stop, increment);
}

function getValue(name) {
    output("Enter " + name + " value:");
    var value = Number(input());
    return value;
}

function whileLoop(start, stop, increment) {
    output("While loop counting from " + start + " to " + stop + 
        " by " + increment + ":");

    var count = start;
    while (count <= stop) {
        output(count);
        count = count + increment;
    }
}

function doLoop(start, stop, increment) {
    output("Do loop counting from " + start + " to " + stop + 
        " by " + increment + ":");
    
    var count = start;
    do {
        output(count);
        count = count + increment;
    } while (count <= stop);
}

function forLoop(start, stop, increment) {
    output("For loop counting from " + start + " to " + stop + 
        " by " + increment + ":");
    
    for (var count = start; count <= stop; count += increment) {
        output(count);
    }
}

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 | edit source]

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 | edit source]