Computer Science 15-110, Spring 2010
Class Notes:  More Loops


  1. Branching Statements
    1. break
    2. continue
    3. Labeled break
    4. Labeled continue
  2. Infinite Loops
    1. while (true)
    2. for ( ; ; )
  3. The do-while Statement
  4. The for Statement
    1. Omitting conditions
    2. Extra conditions
    3. Scope
    4. enhanced for

More Loops

  1. Branching Statements
     
    1. break
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          Scanner scanner = new Scanner(System.in);
          System.out.print("Enter a number to test for primality: ");
          int n = scanner.nextInt();
          boolean isPrime = (n > 1);
          for (int k=2; k<n; k++)
            if (n % k == 0) {
              System.out.println(n + " is divisble by " + k);
              isPrime = false;
              break;
            }
          System.out.println("isPrime = " + isPrime);
        }
      }

      Another Example:

      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          Scanner scanner = new Scanner(System.in);
          int count = 0;
          int sum = 0;
          while (count < 3) {
            System.out.print("Enter # " + (count+1) + " of 3 (or 'q' to quit): ");
            String s = scanner.next();
            if (s.equals("q"))
              break;
            sum += Integer.parseInt(s);
            count++;
          }
          System.out.println("sum = " + sum);
        }
      }
    2. continue
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          Scanner scanner = new Scanner(System.in);
          int count = 0;
          int sum = 0;
          while (count < 3) {
            System.out.print("Enter # " + (count+1) + " of 3 (or 'q' to quit): ");
            if (!scanner.hasNextInt()) {
              String s = scanner.next();
              if (s.equals("q"))
                break;
              else {
                System.out.println("  Not an int: " + s + ".  Please try again.");
                continue;
              }
            }
            sum += scanner.nextInt();
            count++;
          }
          System.out.println("sum = " + sum);
        }
      }
    3. Labeled break
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          System.out.println("This code demonstrates a labeled break.  Note that");
          System.out.println("some people believe you should never use these!");
          System.out.println();
      
          String[] strings = { "abc", "de", "fghij", "klm", "n" };
      
          int i, j=0;
          char key = 'm';
          boolean foundKey = false;
      
          searchForKey:
          for (i=0; i<strings.length; i++)
            for (j=0; j<strings[i].length(); j++)
              if (strings[i].charAt(j) == key) {
                foundKey = true;
                break searchForKey;
              }
      
          if (foundKey == true)
            System.out.println("Found " + key + " at char " + j + " of string " + i);
          else
            System.out.println("Did not find " + key);
        }
      }
    4. Labeled continue
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          System.out.println("This code demonstrates a labeled continue.  Note that");
          System.out.println("some people believe you should never use these!");
          System.out.println();
      
          String string = "We all live on a yellow submarine!";
          String sub = "sub";
      
          int start;
          boolean foundIt = false;
      
          searchForSubstring:
          for (start=0; start<=string.length() - sub.length(); start++) {
            for (int i=0; i<sub.length(); i++) {
              if (sub.charAt(i) != string.charAt(start+i))
                continue searchForSubstring;
            }
            foundIt = true;
            break;
          }
      
          if (foundIt == true)
            System.out.println("Found substring starting at index " + start);
          else
            System.out.println("Did not find the substring");
        }
      }
  2. Infinite Loops
     
    1. while (true)
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          Scanner scanner = new Scanner(System.in);
          int sum = 0;
          int count = 0;
          while (true) {
            System.out.print("Enter # " + (count+1) + " (or 'q' to quit): ");
            String s = scanner.next();
            if (s.equals("q"))
              break;
            sum += Integer.parseInt(s);
            count++;
          }
          System.out.println("sum = " + sum);
        }
      }
    2. for ( ; ; )
      Style Alert:  Do not use "for ( ; ; )" -- use "while (true)"
      
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          Scanner scanner = new Scanner(System.in);
          int sum = 0;
          int count = 0;
          for (;;) {
            System.out.print("Enter # " + (count+1) + " (or 'q' to quit): ");
            String s = scanner.next();
            if (s.equals("q"))
              break;
            sum += Integer.parseInt(s);
            count++;
          }
          System.out.println("sum = " + sum);
        }
      }
  3. The do-while Statement
    import java.util.*;
    class MyCode  {
      public static void main(String[] args) {
        System.out.println("Enter some #'s until their sum exceeds 10.");
        Scanner scanner = new Scanner(System.in);
        int sum = 0;
        do {
          System.out.print("sum = " + sum + ".  Next number: ");
          sum += scanner.nextInt();
        } while (sum <= 10);
        System.out.println("sum = " + sum);
      }
    }
  4. The for Statement
     
    1. Omitting conditions

      Style Alert:  Usually a bad idea, though -- use a better-suited loop

      Ex1:
      int x = 1;
      for ( ; x < 3; x++)
        System.out.println(x);

      Ex2:
      int x = 1;
      for ( ; x < 3; ) {
        x++;
        System.out.println(x);
      }

      Ex3:
      int x = 1;
      for ( ; ; ) {
        x++;
        System.out.println(x);
      }

       
    2. Extra conditions

      Style Alert:  Often a bad idea, though -- put them before the loop or in the body
      int x, y;
      for (x=1,y=5; x < y; x++,y--)
        System.out.println(x);
       
    3. Scope

      Example:
      int x;
      for (x=0; x<2; x++)
        System.out.println(x);

      Roughly the same as:
      for (int x=0; x<2; x++)
        System.out.println(x);

      But:  variable's scope is limited to the for loop:
      int x;
      for (x=0; x<2; x++)
        System.out.println(x);
      System.out.println(x);

      Cannot be done this way:
      for (int x=0; x<2; x++)
        System.out.println(x);
      System.out.println(x);  // will not compile, x is not in scope here!

      Also:  cannot declare a local variable within the scope of another local variable of the same name
      int x;
      for (int x=0; x<2; x++)  // will not compile -- x is already defined!
        System.out.println(x);

      But you can reuse variables in subsequent for loops:

      for (int x=0; x<2; x++)
        System.out.println(x);

      for (int x=0; x<2; x++)
        System.out.println(x);

       

    4. enhanced for

      We will review the enhanced for loop when we cover arrays and/or the JCF.

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem