Difference between revisions of "While Loops"

From CompSciWiki
Jump to: navigation, search
(adding a preface to the syntax.)
(added example.)
Line 39: Line 39:
 
==Syntax==
 
==Syntax==
  
In java, the while loop takes the form of
+
In java, the general form of a while loop is
 
<pre>
 
<pre>
while(test_condition)
+
while(test_condition){
{
+
 
   ...
 
   ...
 
   statements;
 
   statements;
Line 49: Line 48:
 
</pre>
 
</pre>
 
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.
 
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.
 +
 +
===Example:  User Input===
 +
 +
A while loop can be used to ensure that the user inputs a positive integer.
 +
 +
<pre>
 +
String input;
 +
int userInput;
 +
 +
input = JOptionPane.showInputDialog("Enter a positive integer.");
 +
userInput = Integer.parseInt(input);
 +
 +
while (userInput < 0) {
 +
  input = JOptionPane.showInputDialog("I'm sorry, the number you entered was not positive. Please enter a positive integer..");
 +
  userInput = Integer.parseInt(input);
 +
}
 +
JOptionPane.showMessageDialog("Thank you. The number you entered was " + userInput +".");
 +
</pre>
 +
 +
There are a few things worth noting about this while loop.
 +
# When the two lines of code before the while loop are executed, it is possible that the user actually does input a positive integer on the first try.  In this case, when execution reaches the while loop, the test condition is false (since <tt>userInput >= 0</tt> and the two lines of code within the while loop are not executed.
 +
# On the other hand, if the user doesn't input a positive integer, the loop condition is true. In this case, the loop body is executed, and the input is read again. 
 +
# An important part of the body of the while loop is that it reads a new input value, but stores it in the same variable <tt>userInput</tt>.  In this way, when the body has been executed, and control returns to the condition at the top of the loop, we are comparing the new value of <tt>userInput</tt> and testing <tt>userInput</tt> &lt; <tt>0</tt>.
 +
# After the loop has successfully completed (when the user eventually inputs a positive integer), the last value of <tt>userInput</tt> is still the one that was positive. So, the value that is displayed by <tt>JOptionPane</tt> is the last (positive) value the user entered.
  
 
==Uses==
 
==Uses==

Revision as of 11:22, 4 August 2010

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. The first type of loop we will examine is the while loop.

Elements of a While Loop

A while loop needs two things:

  1. the body of the loop. These are the statements that are repeated. Each time through the loop the same body is executed.
  2. a conditional. Similar to an if statement, this is a boolean test condition, which could involve comparisons like ==, <= or .equals.

A while loop will test the conditional, and if it evaluates to true, the body of the loop is executed. If it is false, the body of the loop is skipped over (like an if statement) and execution continues directly after the loop. But (unlike an if statement), if the body of the loop is executed, after execution the flow of control returns to the loop condition, which is tested again. And again, if it is true, the body is exceuted, otherwise it is skipped.

Syntax

In java, the general form of a while loop is

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.

Example: User Input

A while loop can be used to ensure that the user inputs a positive integer.

String input; 
int userInput;

input = JOptionPane.showInputDialog("Enter a positive integer.");
userInput = Integer.parseInt(input);

while (userInput < 0) {
  input = JOptionPane.showInputDialog("I'm sorry, the number you entered was not positive. Please enter a positive integer..");
  userInput = Integer.parseInt(input);
}
JOptionPane.showMessageDialog("Thank you. The number you entered was " + userInput +".");

There are a few things worth noting about this while loop.

  1. When the two lines of code before the while loop are executed, it is possible that the user actually does input a positive integer on the first try. In this case, when execution reaches the while loop, the test condition is false (since userInput >= 0 and the two lines of code within the while loop are not executed.
  2. On the other hand, if the user doesn't input a positive integer, the loop condition is true. In this case, the loop body is executed, and the input is read again.
  3. An important part of the body of the while loop is that it reads a new input value, but stores it in the same variable userInput. In this way, when the body has been executed, and control returns to the condition at the top of the loop, we are comparing the new value of userInput and testing userInput < 0.
  4. After the loop has successfully completed (when the user eventually inputs a positive integer), the last value of userInput is still the one that was positive. So, the value that is displayed by JOptionPane is the last (positive) value the user entered.

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.