Three Loops for Novice Programmers
Do you know how these three loops work? Take your time and think about the output of them. ^ ^
Three Loops
public class Loops {
public void forLoop() {
int i = 0;
for (; i < 3; i++) {
System.out.println("Inside of the for loop: i = " + i);
}
System.out.println("Outside of the for loop: i = " + i);
}
public void whileLoop1() {
int i = 0;
while (i++ <= 1) {
System.out.println("Inside of the while loop1: i = " + i);
}
System.out.println("Outside of the while loop1: i = " + i);
}
public void whileLoop2() {
int i = 0;
while (++i <= 1) {
System.out.println("Inside of the while loop2: i = " + i);
}
System.out.println("Outside of the while loop2: i = " + i);
}
public static void main(String[] args) {
Loops loops = new Loops();
loops.forLoop();
System.out.println();
loops.whileLoop1();
System.out.println();
loops.whileLoop2();
}
}
Output
Inside of the for loop: i = 0
Inside of the for loop: i = 1
Inside of the for loop: i = 2
Outside of the for loop: i = 3
Inside of the while loop1: i = 1
Inside of the while loop1: i = 2
Outside of the while loop1: i = 3
Inside of the while loop2: i = 1
Outside of the while loop2: i = 2
They’re pretty intuitive, aren’t they?