While Loops


While loops

Java has a while-loop that is similar in spirit to a Cinnameg while loop. A Java while-loop has the form

  while ( expression )
    statement
where the expression must produce a boolean result. Java program fragment
  int x = 0;
  int r = 0;
  while(x < 10)
  {
    x = x + 1;
    r = r + x;
  }
is equivalent to Cinnameg program fragment
  Let x: Integer = 0.
  Let r: Integer = 0.
  While x < 10 do
    Relet x = x + 1.
    Relet r = r + x.
  %While

There are differences in appearance between the Java while-loop and the Cinnameg While-loop.

  1. In Java, while is all lower case letters. Do not capitalized it.

  2. In Java you do not write do. The body of the loop immmediately follows the condition.

  3. In Java, the condition being tested is required to be surrounded by parentheses. Leaving off the parentheses will cause an error.

  4. In Java, there is no end of while marker.

  5. In Java, just one statement follows the condition. You typically use a compound statement to include several statements.


Context

The body of a while-loop is always a context. Variables created in the body are destroyed as soon as the program is done with the loop.


Breaking out of a loop

Java allows you to request ending a loop at any point inside the loop body. Use statement break; for that. For example, the following loop might be used to tell if a number n is prime.

  int k = 2;
  while(k < n)
  {
    if(n % k == 0) break;
    k++;
  }
When the loop is done, k will equal n if n is prime, and will be less than n if n is not prime.


More information

While-loops are discussed in Chapter 4.1 of Savitch and Carrano. That chapter also discusses additional kinds of loops: the do-loop, the for-loop and the for-each-loop. We will encounter the for-loop later, but will not cover do-loops or for-each-loops.


Problems

  1. [solve] Suppose that variables x and n, both of type int, have already been created and given values. The value of n is a positive integer. Write statements that will create variable y, of type int, and will make y equal to xn (x to the n-th power). Use a loop to accumulate the power. You can also create other variables to use.


Summary

A Java while-loop has the same idea as a Cinnameg While-loop. But there are some differences in appearance.

A while-loop is always a context. Variables that are created inside the loop body are destoyed at the end of the loop body.