Prev Main Next

Breaking Loops

Inside the body of a loop, you can ask to get out of the loop right away. Use a break statement. It is just

  break;


Example

If you are searching for something, you usually want to stop the search right away when you find it. For example, an integer is composite if it is larger than one and it has a factor other than itself and 1. For example, 39 is composite since 3 is a factor of 39. (39 = 3*13.) (Composite is the opposite of prime.)

To tell if a number is composite, the obvious thing to do is to look for a factor. If you want to know whether number n is composite, try 2, 3, 4, 5, 6, ..., n-1, checking whether each is a factor.

But when you find a factor, there is no need to keep going. You know the answer. Here is a loop that breaks as soon as it finds a factor of n. If presumes that variable n already has a value. For simplicity, assume that you know that n > 1.

  int i;
  for(i = 2; i < n; i++) 
  {
    if(n % i == 0) break;
  }
But after you get out of the loop, how can you know whether you got out because you found a factor of n, or because you ran out of numbers to test?
  1. Well, you only go into the loop when i < n. You can see that from the condition in the heading. When the loop breaks, it does not change i, so it would still be the case that i < n after the loop.

  2. If the loop finishes because the condition i < n is false, then it must be the case that i >= n. (In fact, i will have to be equal to n.)

So you can find out whether a break was done by comparing i to n. The following program fragments sets variable isComposite to true if n is composite, and to false if n is not composite.
  boolean isComposite;
  int i;
  for(i = 2; i < n; i++) 
  {
    if(n % i == 0) break;
  }
  if(i < n) isComposite = true;
  else isComposite = false;


Question. Does the above program fragment give the correct answer if n = 1? If not, how can it be fixed? Remember that, by definition, 1 is not composite. (1 is a special number that is neither prime nor composite.) Answer[28]


Prev Main Next