Bounds from input
Both ends of a loop can come from the input. The loop then runs as many rounds as the numbers say:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int from = Integer.valueOf(scanner.nextLine());
int to = Integer.valueOf(scanner.nextLine());
for (int i = from; i <= to; i++) {
System.out.println(i);
}
System.out.println("End");
}
}
-2
1-2
-1
0
1
EndWhat if the start is bigger than the end, say from 5 to 3? The condition 5 <= 3 is false before the first round, so the loop's block doesn't run at all, and the program goes straight on to End. A loop that runs zero times is normal, and a program should still print something sensible when it happens.