While Loops
Example:
int x = 1;
while (x < 5)
{
System.out.println("Looping");
x = x + 1;
}
System.out.println("Done");
Infinite Loops
One easy mistake to make when working with loops is accidently creating an infinite loop. An infinite, or endless, loop is a loop that never exits and loops forever, or at least until the power goes out. There are two main types of infinite loops:
Always have an exit condition defined, either within the loop itself or with a break statement.
Break Statements
You can use a break to exit a loop early
Example:
x = 1;
while (x < 5)
{
if (x == 3)
{
break;
}
System.out.println("Looping");
x = x + 1;
}
System.out.println("Done");
How it work:
Practice
What would the following program output?
x = 0;
System.out.println("A");
while (x <= 3)
{
System.out.println("B");
x = x + 1;
}
System.out.println("C")
How it work: