PreLab 8: While Loops

The following is a basic loop that prints the numbers from 1 to LIMIT and finds their sum:

   final int LIMIT = 100;         // setup
   int count = 1;                 // - initialize the loop control variable 
   int sum = 0;                   // - and the summing variable

   while (count <= LIMIT)         // condition
   {                              // body
     System.out.println(count);   //   -- perform task
     sum = sum + count;           //      (print and sum)
     count = count + 1;           //   -- update condition
   }
   System.out.println ("The sum of the integers from 1 to " +
        LIMIT + " is " + sum);

This loop is an example of a count-controlled loop, that is, a loop that contains a counter (a variable that increases or decreases by a fixed value -- usually 1 -- each time through the loop) and that stops when the counter reaches a certain value. Not all loops with counters are count-controlled; consider the example below, which determines how many even numbers must be added together, starting at 2, to reach or exceed a given limit.

   final int LIMIT = 16;                            TRACE
   int count = 1;                        sum        nextVal     count
   int sum = 0;                          ---        -------     -----
   int nextVal = 2;

   while (sum < LIMIT)
   {
     sum = sum + nextVal;     
     nextVal = nextVal + 2;
     count = count + 1;
   }
  
   System.out.println("Had to add together " + (count-1) + " even numbers " +
                      "to reach value " + LIMIT + ".  Sum is " + sum);
Note that although this loop counts how many times the body is executed, the condition does not depend on the value of count.

Not all loops have counters. For example, if the task in the loop above were simply to add together even numbers until the sum reached a certain limit and then print the sum (as opposed to printing the number of things added together), there would be no need for the counter. Similarly, the loop below sums integers input by the user and prints the sum; it contains no counter.

   int sum = 0;                                         //setup
   String keepGoing = "Y";
   int nextVal;

   while (keepGoing.equals("y") || keepGoing.equals("Y")
   {
    System.out.print("Enter the next integer: ");       //do work
    nextVal = scan.nextInt();
    sum = sum + nextVal;

    System.out.println("Type y or Y to keep going");    //update condition
    keepGoing = scan.next();
   }

   System.out.println("The sum of your integers is " + sum);

Exercises

  1. In the first loop above, the println statement and the statement to update the sum comes before the value of count is incremented. What would happen if you reversed the order of these statements so that count was incremented before the other two statements? Would the loop still print the same values? Would the sum be the same? Explain.




  2. Consider the second loop above.
    1. Trace this loop, that is, in the table next to the code show values for variables nextVal, sum and count at each iteration. Then show what the code prints.
    2. Note that when the loop terminates, the number of even numbers added together before reaching the limit is count-1, not count. How could you modify the code so that when the loop terminates, the number of things added together is simply count?




  3. Write a while loop that will print "I love computer science!!" 100 times. Is this loop count-controlled?







  4. Add a counter to the third example loop above (the one that reads and sums integers input by the user). After the loop, print the number of integers read as well as the sum. Just note your changes on the example code. Is your loop now count-controlled?


  5. The code below is supposed to print the integers from 10 to 1 backwards. What is wrong with it? (Hint: there are two problems!) Correct the code so it does the right thing.

       count = 10;
       while (count >= 0)
       {
        System.out.println(count);
        count = count + 1;
       }