while loop
Definition
A while loop is a programming construct that is used to repeat the execution of one or more statements. While loops are a good choice when you do not know exactly how many times you want the loop to run.
Execution
The loop will be executed in the following order:
- initialization(s)
- condition check (if false the loop is over)
- loop body
- update(s)
- go to step 2
Code
This is a code to convert from base 10 to another base:
int num = 100; int base = 2; System.out.print (num%base); while (num / base != 0) { num = num / base; System.out.print (num % base); }
In the case above, we do not necessarily know how many times we want to loop through. The program
will keep looping until num / base == 0. The program above will print 1100100.
Do while
A do while is useful when you want the loop body to execute at least once.