View this PageEdit this PageAttachments to this PageHistory of this PageHomeRecent ChangesSearch the SwikiHelp Guide

Loops

Know 3 types of loops: for-each, while, and for. Also know that recursion can be used to loop. Also know how to do nested for loops. Know how many times a loop exectues (endValue - startValue + 1). Know that the number of time an inner loop executes in a nested loop is the number of times the outer loop executes multiplied by the number of times the inner loop executes.

When to use each type:

Things to be careful about:

For-each example:

If you have an array of integer values and you want to add them all just use a for-each loop:
public static int total(int[] arr)
{
   int total = 0;
   for (int value : arr)
   {
      total = total + value;
   }
}


Practice: http://codingbat.com/prob/p184031 and http://codingbat.com/java/Array-2
Also see: http://codingbat.com/doc/array.html


While example:

If you want to do a binary search for a value in a sorted array of Strings:
 public static int binaryFind(String target, String[] listArray)
  {
    int start = 0;
    int end = listArray.length - 1;
    int checkpoint = 0;

    while (start <= end)
    { //While there are more to search
      // find the middle
      checkpoint = (start+end)/2;
      System.out.println("Checking at: "+
       checkpoint+" start="+start+" end="+end);
      if (target.compareTo(listArray[checkpoint]) == 0)
      {
        return checkpoint;
      }
      else if (target.compareTo(listArray[checkpoint]) > 0)
      {
        start=checkpoint + 1;
      }
      else if (target.compareTo(listArray[checkpoint]) < 0)
      {
        end=checkpoint - 1;
      }
    }
    return -1;
  }


Practice: See question 1 at http://coweb.cc.gatech.edu/ice-gt/1280 and http://webster.cs.washington.edu:8080/practiceit/problem.jsp?category=Chapter+5&problem=5-s3-whileLoopMystery1 and http://webster.cs.washington.edu:8080/practiceit/problem.jsp?category=Chapter+5&problem=5-s4-whileLoopMystery2
Also see: http://codingbat.com/doc/loop.html

Example For Loop
These are great to use when you want to loop through part of an array or list. In the code below we are looking for the largest and smallest values in an array
and returning the difference between the largest and smallest values. An easy way to do this is to use the first value in the array as the current largest and smallest and then loop through the rest of the array looking for any larger or smaller.
public int bigDiff(int[] nums) {
  int largest = nums[0];
  int smallest = nums[0];
  for (int i = 1; i < nums.length; i++)
  {
    if (nums[i] > largest) largest = nums[i];
    else if (nums[i] < smallest) smallest = nums[i];
  }
  return largest - smallest;
}



Practice: http://codingbat.com/prob/p136585

Nested for loop example

Practice: http://webster.cs.washington.edu:8080/practiceit/search.jsp?keyword=nested+loops

Link to this Page