FOR loops are a good way of providing iteration in a programming language. While loops can be considered as a more general form of a for loop. They only use condition and rely on the programmer to fill in the blanks. Consider the for loop below-

  1. for (int a=0; a<=10; a = a + 1){
  2. System.out.println(a);
  3. }

Here is the equivalent while loop -

  1. int a=0
  2. while(a<=10){
  3. System.out.println(a);
  4. a = a + 1
  5. }

The major differences have been highlighted in bold. The biggest difference is that while loops only have a condition. In order for the loop to occur the condition must evaluate to true. As soon as it evaluates to false the loop will terminate.

  1. boolean flag = true;
  2. while(flag){
  3. if (flag == true) flag = !flag;
  4. }

Here is a while loop which does not use a counter. It is much more common to use a while loop to when you do not have a counter rather than a for loop. This is mainly as the for loop statement for this would look like this

for(;flag;)

or maybe

for(boolean flag = true; flag;)

If you do not understand this code then look up the section on IF statements! Remember the condition for both for and while (like if) must evaluate to a boolean. So the above code is perfectly valid. You can also skip out parts of a for loop should you wish. The following code will prioduce a infinite loop -

  1. for(;;){
  2. System.out.println("Infinite loop");
  3. }

There are important differences between a WHILE loop and a FOR loop -

next do while / repeat until >>

 
Basics
Menu
Search