Difference between revisions of "While Loops"

From CompSciWiki
Jump to: navigation, search
(Inserted an overview)
(Change of wording)
Line 11: Line 11:
 
}
 
}
 
</pre>
 
</pre>
The while will execute all of the instructions inside of the [[Methods and Scoping|block]] following it. The instructions in the block will execute as long as the [[test condition]] is true. When the test condition evaluates to false the program continues with the instructions following the block.
+
The while will execute all of the instructions inside of the [[Methods and Scoping|block]] of code following it. The instructions in the block of code will execute as long as the [[test condition]] is true. When the test condition evaluates to false the program continues with the instructions following the block.
  
 
==Uses==
 
==Uses==
A while loop is useful in any situation where the number of iterations for a block of code is not known.
+
While loops are very useful in any situation where a certain section of code needs to be repeated while a certain condition is true.
 
For example: If you want to loop until the user gives specific input. Below is an example of a while loop that iterates until the user enters the string 'quit'.
 
For example: If you want to loop until the user gives specific input. Below is an example of a while loop that iterates until the user enters the string 'quit'.
  

Revision as of 22:23, 5 December 2007

COMP 1010 Home > Loops


Introduction

The while loop is the most basic form of a loop. The loop continues to repeat as long as the test condition evaluates to true.

   

{{{Body}}}

Syntax

In java, the while loop takes the form of

while(test_condition)
{
   ...
   statements;
   ...
}

The while will execute all of the instructions inside of the block of code following it. The instructions in the block of code will execute as long as the test condition is true. When the test condition evaluates to false the program continues with the instructions following the block.

Uses

While loops are very useful in any situation where a certain section of code needs to be repeated while a certain condition is true. For example: If you want to loop until the user gives specific input. Below is an example of a while loop that iterates until the user enters the string 'quit'.

import javax.swing.JOptionPane;

public class Input
{
  public static void main(String args[]) 
  {
    String name;
    name = JOptionPane.showInputDialog("Enter a name, type quit to finish");
    
    while(!name.equals("quit"))
    {
         System.out.println("Hello " + name);
         name = JOptionPane.showInputDialog("Enter a name, type quit to finish");
    }
  }
}

The instruction !name.equals("quit") is the test condition. It evaluates to true until quit is entered.