Programming Fundamentals/Loop Examples JavaScript

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Counting[edit]

// 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);
  }
}

Output[edit]

Enter starting value:
1
Enter ending value:
3
Enter increment value:
1
While loop counting from 1 to 3 by 1:
1
2
3
Do loop counting from 1 to 3 by 1:
1
2
3
For loop counting from 1 to 3 by 1:
1
2
3

References[edit]