While Loops

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > Loops


Introduction

The while loop is the most basic form of loop. The loop repeats as long as the test condition evaluates to true.

Elements of a While Loop

A while loop needs two things:

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

When a while loop is implemented, the program will test the conditional statement. If it evaluates to true, the body of the loop is executed. If it evaluates to false, the body of the loop is skipped over (like an if statement) and execution of the program continues directly after the loop. However, unlike an if statement, if the conditional statement evaluates to true and the body of the loop is executed, after execution the flow of control returns to the top of the loop (the conditional statement), which is tested again. Once again, if it evaluates to true, the body is executed, otherwise it is skipped.

Syntax

In java, the general form of a while loop is

 while(test_condition){
   ...
   statements;
   ...
} 

The program will execute all of the instructions inside of the block of code following the test condition. The instructions in the block of code will continue to be executed 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 enters a positive integer on the first try. In this case, when execution reaches the while loop, the test condition evaluates to false (since userInput >= 0. In this case, the two lines of code within the body of the while loop are not executed.
  2. On the other hand, if the user doesn't input a positive integer, the loop condition evaluates to true. In this case, the loop body is executed, and the user is again asked to enter a positive integer.
  3. An important part of the body in this 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. In this case, the only way to successfully complete the loop is for the user to input a positive integer. So, when the loop is completed, the value of userInput is the positive value entered by the user. Therefore, 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: In each iteration, all it does is increment the value of approxSqrt by one. The loop continues to iterate until it finds a value of approxSqrt such that approxSqrt2 is greater than or equal to input. When this value is found, 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: Looping 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 the String '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 times, 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, because numTimes is initialized to 0. Also, remember that numTimes must be initialized before the loop executes (see example below).

Common Pitfalls

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

Error: Not reusing variables.

Here's our example again, 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, the execution of the program will enter the while loop. This loop will then 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 will be executed. 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 enters.

To solve this problem, always make sure you are modifying something related to your conditional statement each time the program goes 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 initialized (given a value), which is exactly what has happened. The code tries to read the value of userInput before it is assigned a value. In the previous example, we solved this by asking the user for input before the loop was executed. This is sometimes called "priming" the while loop.

Error: Not updating the 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 is always equal to zero. To avoid this problem, add an increment statement somewhere in the body of your while loop (most often at the end). If you routinely find yourself with this error, you might consider rewriting your loop as a for loop (see section on for loops for instructions).

Previous Page: Looping Next Page: Do-While Loops