Difference between revisions of "While Loops"

From CompSciWiki
Jump to: navigation, search
(Inserted an overview)
Line 1: Line 1:
{{1010Topic|Introduction=The while loop is the most basic form of a [[Loops|loop]]. The loop continues to repeat as long as the [[test condition]] evaluates to ''true''.|Chapter_TOC=[[Loops]]}}
+
{{1010Topic|Introduction=The while loop is the most basic form of a [[Loops|loop]]. The loop continues to repeat as long as the [[test condition]] evaluates to ''true''.|Overview = By the end of this section, you would have learnt when and how to use the while loop.|Chapter_TOC=[[Loops]]}}
  
 
==Syntax==
 
==Syntax==

Revision as of 15:16, 3 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 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.