C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: We increment "i" upwards and decrement "z" downwards. When "i" is no longer smaller than "z," the loop ceases.
Thus: In programs, for-loops are more often useful. But in cases where the loop termination is unknown, a while-loop shines.
Java program that uses while-loop
public class Program {
public static void main(String[] args) {
int i = 0;
int z = 10;
// Loop with two variables.
while (i < z) {
i++;
z--;
// Display the values.
System.out.println(i + "/" + z);
}
}
}
Output
1/9
2/8
3/7
4/6
5/5
However: The break statement terminates the loop. No further iterations are run.
Here: This program will continue looping in the while-loop until it reaches a random number greater than 0.8.
RandomJava program that uses break, while-true
import java.lang.Math;
public class Program {
public static void main(String[] args) {
// Loop infinitely.
while (true) {
// Get random number between 0 and 1.
double value = Math.random();
System.out.println(value);
// Break if greater than 0.8.
if (value >= 0.8) {
break;
}
}
}
}
Output
0.16129889659284657
0.0977987643977064
0.859556475501672
Sometimes: A do-while loop can make programs faster by reducing the number of checks done.
Java program that uses do-while
public class Program {
public static void main(String[] args) {
int i = 0;
// Loop while the variable is less than 3.
// ... It is not checked on the first iteration.
do {
System.out.println(i);
i++;
} while (i < 3);
}
}
Output
0
1
2
Modulo: We also use a modulo test to see if a number is evenly divisible by 2. We use the continue statement to stop the current iteration.
ModuloJava program that uses while, post increment, continue
public class Program {
public static void main(String[] args) {
int index = 0;
// Use post increment in while-loop expression.
while (index++ < 10) {
// Continue if even number.
if ((index % 2) == 0) {
continue;
}
System.out.println("Element: " + index);
}
}
}
Output
Element: 1
Element: 3
Element: 5
Element: 7
Element: 9