Difference between revisions of "While Loops"

From CompSciWiki
Jump to: navigation, search
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.
+
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.
  
 
==Uses==
 
==Uses==

Revision as of 12:14, 27 November 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 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.

Uses

A while loop is useful in any situation where the number of iterations for a block of code is not known. 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.