JavaScript Examples

Dave Braunschweig

Counting

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

    demonstrateWhileLoop(start, stop, increment);
    demonstrateDoLoop(start, stop, increment);
    demonstrateForLoop(start, stop, increment);
}

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

function demonstrateWhileLoop(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 demonstrateDoLoop(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 demonstrateForLoop(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

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

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Programming Fundamentals Copyright © 2018 by Dave Braunschweig is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book