While Loops
Loops are used in programming to repeat the execution of code instead of writing the line code of over and over again.
A Code Example
Line by Line Analysis
We have set an outer variable to help us with our while loop.
While is a keyword in java.
It helps us start a looping structure.
Much like an if statement a while loop will execute its code block when its boolean expression is true.
Unlike an if statement, a while loop will continue to execute its code block as long as the boolean expression is true.
This line of code just decrements countdown variable by 1 at every iteration.
Formalization
Iterations: instructions or code being repeated until a specific end result is achieved.
While Loop Format in Java:
Infinite Loop: An infinite loop is a while loop that never ends because the boolean condition of the loop never turns to false.
Example:
Using While Loops as a Counter
By using some sort of a counting variable, you get to control the number of iterations you execute.
Using a boolean variable to control when to end a while loop
We can also take an user input every iteration to check if they want to exit to prevent an infinite loop.
Last updated