Programming Fundamentals/Loop Examples Java
Appearance
Counting
[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/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);
}
}
}
Output
[edit | edit source]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