Prev Main Next

While Loops

A computer program often needs to do a great deal of computing. For example, if you have a picture, and you want to convert it to its negative image by changing the colors. Then you need to change every pixel (dot) in the picture.

A while loop is one way to do something over and over. You generally write a while loop as follows.

  (initialization)
  while(condition)
  {
    statements
  }
where you put in appropriate things for the parts in red. the statements inside the braces are called the loop body.

Note. The parentheses around the condition are required. If you omit them, then you will get an error.

Warning. Do not put a semicolon at the end of the line that starts while. You will create a loop that never stops.


Example

Suppose that you want to make variable sum hold 1 + 2 + ... + 100. The following accumulates the sum, by starting it at 0, then adding 1, then adding 2, etc.

  int k, sum;
  sum = 0;
  k = 1;
  while(k <= 100) 
  {
    sum = sum + k;
    k = k + 1;
  }


Remarks



Questions.

  1. Suppose that variable n has already been created, and has type int. Is the following allowed?

        n = 1;
        while n < 10
        {
          n = n + 1;
        }
      
    Answer[21]

  2. Suppose that variable n has already been created, and has type int. Is the following allowed?

        n = 1;
        While(n < 10)
        {
          n = n + 1;
        }
      
    Answer[22]

  3. What does the following print at the System.out.println line?

        int r,s;
        r = 1;
        s = 1;
        while(r != 5) 
        {
          s = s + s + 1;
          r = r + 1;
        }
        System.out.println(s);
      
    (Work it out before you look at the answer[23].)

  4. [Suppose that C is an ordinary boolean expression (one without side-effects). The expressions that we have seen do not have side-effects.] Do the following program fragments always do the same thing, regardless of what which condition is substituted for C or which statement is substituted for S? The first is

        while(C)
        {
          S
        }
      
    The second is
        if(C)
        {
          while(C)
          {
            S
          }
        }
      
    Answer[24]


Prev Main Next