Programming Fundamentals/Loops/Java
loops.java
edit// 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");
whileLoop(start, stop, increment);
doLoop(start, stop, increment);
forLoop(start, stop, increment);
}
public static int getValue(String name) {
System.out.println("Enter " + name + " value:");
int value = input.nextInt();
return value;
}
public static void whileLoop(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 doLoop(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 forLoop(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);
}
}
}
Try It
editCopy and paste the code above into one of the following free online development environments or use your own Java compiler / interpreter / IDE.