while loop


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.


The loop will be executed in the following order:

  1. initialization(s)
  2. condition check (if false the loop is over)
  3. loop body
  4. update(s)
  5. go to step 2


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.


Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License