Difference between revisions of "While Loops"

From CompSciWiki
Jump to: navigation, search
m
Line 95: Line 95:
 
The body of this loop is very simple: it only increments the value of <tt>approxSqrt</tt> by one to check the next value. The loop continues until it finds a value of <tt>approxSqrt</tt> such that <tt>approxSqrt</tt><sup>2</sup> is greater than or equal to <tt>input</tt>.  When it finds this value, the loop quits.  So, after the loop is completed, we have a value <tt>approxSqrt<tt> that is greater than (or equal to) the square root of <tt>input</tt>, but  
 
The body of this loop is very simple: it only increments the value of <tt>approxSqrt</tt> by one to check the next value. The loop continues until it finds a value of <tt>approxSqrt</tt> such that <tt>approxSqrt</tt><sup>2</sup> is greater than or equal to <tt>input</tt>.  When it finds this value, the loop quits.  So, after the loop is completed, we have a value <tt>approxSqrt<tt> that is greater than (or equal to) the square root of <tt>input</tt>, but  
 
<tt>approxSqrt-1</tt> is less than the square root of <tt>input</tt>.
 
<tt>approxSqrt-1</tt> is less than the square root of <tt>input</tt>.
 
 
 
==Uses==
 
==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.
 
While loops are very useful in any situation where a certain section of code needs to be repeated while a certain condition is true.

Revision as of 15:31, 6 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.

Example: approximating the square root

Remember that the square root of a number x is the number y which satisfies y2 = x. We can find the approximate value of the square root of a number using a while loop:

String inp;
int input;
int approxSqrt =1;

inp = JOptionPane.showInputDialog("Enter a number");
input = Integer.parseInt(inp);
		
while (Math.pow(approxSqrt,2) < input) {
	approxSqrt++;
}
JOptionPane.showMessageDialog(null, "The square root of " + input + 
	" is between " + (approxSqrt-1) + " and " + approxSqrt +".");

The body of this loop is very simple: it only increments the value of approxSqrt by one to check the next value. The loop continues until it finds a value of approxSqrt such that approxSqrt2 is greater than or equal to input. When it finds this value, the loop quits. So, after the loop is completed, we have a value approxSqrt<tt> that is greater than (or equal to) the square root of <tt>input, but approxSqrt-1 is less than the square root of input.

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.

When you have a loop that you know will execute a certain number of times (e.g., ten times, one hundred times, etc.) then a while loop will work, but it may be easier to use a for loop. To write a while loop which executes a certain number of time use a counter:

int numTimes = 0;

while (numTimes <= 10) { 
  System.out.println("this is the " + numTimes + "-th time through the loop.");
  numTimes++;
}

Note that this loop will execute 11 times: once for each value 0 through 10. Also, remember that you must set a value for numTimes before the loop executes.

Common Pitfalls

Here are some common errors that can happen when you write a while loop.

Error: Not reusing variables.

Here's our example, slightly changed:

String input; 
int newuserInput, 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..");
  newuserInput = Integer.parseInt(input);
}
JOptionPane.showMessageDialog("Thank you. The number you entered was " + userInput +".");

If the user inputs a negative value to start, this loop will execute forever; it is an infinite loop. The reason is that if the first value of userInput is, say, -1, then the condition on the while loop is true, and the body is executed. But in this case, whatever the user inputs is stored in the variable newuserInput, which is not compared against zero in the loop condition. In fact, since userInput is still -1, the loop will execute forever, regardless of what the user inputs.

To solve this problem, always make sure you are modifying something related to your condition each time through the body of the loop.

Error: Not "priming" the loop

Consider the user input example again:

String input; 
int userInput;

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 +".");

This code will not compile: Java will tell you that the variable userInput is used before it is given a value, which is exactly what is happening. The code tries to read the value of userInput before it is given a value. In the previous example, we solved this by asking for the user for the input once before the loop executes. This is sometimes called "priming" the while loop.

Error: Not updating your counter

When running a while loop a set number of times, remember that it is up to you to increment your counter variable:

int numTimes = 0;

while (numTimes <= 10) { 
  System.out.println("this is the " + numTimes + "-th time through the loop.");
}

This loop will again execute forever, since numTimes never changes to any value other than zero. Make sure to add an increment statement somewhere in the body of your while loop. If you routinely find yourself with this error, you might consider rewriting your loop as a for loop.