While Loops

From CompSciWiki
Revision as of 10:50, 4 August 2010 by Mdomarat (Talk | contribs)

Jump to: navigation, search

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}}}

Looping

A loop is a block of code that may execute zero, one or more times. As an example, think about writing a program that would read in ten numbers from the user. With the tools we have up to now, we would end up with a program that looks something like:

String input;
int input1, input2, input3, input4, input5, input6, input7, input8, input9, input10;

input = JOptionPane.showInputDialog("Enter number 1:");
input1 = Integer.parseInt(input);

input = JOptionPane.showInputDialog("Enter number 2:");
input2 = Integer.parseInt(input);

// etc

input = JOptionPane.showInputDialog("Enter number 10:");
input10 = Integer.parseInt(input);

This program has (at least) two problems:

  1. Writing the code is repetitive: you have to write the same block of code (with minor changes) ten times.
  2. The code is not general purpose: in order to modify your code to accept, say, twenty numbers, you'd have to go and change your code.

In order to write code that fixes these two problems, we will study loops. Loops are blocks of code where we have control over how many times the code executes. It could execute zero times, one time, or more, depending on conditions that we place in the code.

The conditions that we place will be the same as the conditions in if statements: they will be boolean conditions that tell us when to stop executing the code in the loop.

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.