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/Java_Programming

import java.util.*;

public class Main {
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        int start = getValue("starting");
        int stop = getValue("ending");
        int increment = getValue("increment");

        demonstrateWhileLoop(start, stop, increment);
        demonstrateDoLoop(start, stop, increment);
        demonstrateForLoop(start, stop, increment);
    }
    
    public static int getValue(String name) {
        System.out.println("Enter " + name + " value:");
        int value = input.nextInt();
        
        return value;
    }
    
    public static void demonstrateWhileLoop(int start, int stop, int increment) {
        System.out.println("While loop counting from " + start + " to " + 
            stop + " by " + increment + ":");
        
        int count = start;
        while (count <= stop) {
            System.out.println(count);
            count = count + increment;
        }
    }
    
    public static void demonstrateDoLoop(int start, int stop, int increment) {
        System.out.println("Do loop counting from " + start + " to " + 
            stop + " by " + increment + ":");
        
        int count = start;
        do {
            System.out.println(count);
            count = count + increment;
        } while (count <= stop);
    }
    
    public static void demonstrateForLoop(int start, int stop, int increment) {
        System.out.println("For loop counting from " + start + " to " + 
            stop + " by " + increment + ":");
        
        for (int count = start; count <= stop; count += increment) {
            System.out.println(count);
        }
    }
}

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