Computer Science 15-110, Spring 2010
Class Notes:  Loops (An Introduction)


  1. The "for" statement
    1. Print the numbers from 1 to 5
    2. Print the numbers from 1 to n
    3. Print the sum of the numbers from 1 to n
    4. Print the sum of the odd numbers from 1 to n
      1. Using "if"
      2. Using a different increment
    5. Print the letters in a String
    6. Print the letters in a String in reverse
  2. Example:  isPrime
  3. The "while" statement
    1. Division by Subtraction
    2. Another "while" Example
  4. Example:  nthPrime
  5. Sample code:  isPrime and nthPrime
  6. Nested Loops
  7. Nested Loops in Graphics

Loops

  1. The "for" statement
     
    1. Print the numbers from 1 to 5
      class MyCode {
        public static void main(String[] args) {
          int counter;
          for (counter=1; counter<=5; counter++) {
            System.out.println(counter);
          }
        }
      }
    2. Print the numbers from 1 to n
      class MyCode {
        public static void main(String[] args) {
          int counter;
          int n = 10;
          for (counter=1; counter<=n; counter++) {
            System.out.println(counter);
          }
        }
      }
    3. Print the sum of the numbers from 1 to n
      class MyCode {
        public static void main(String[] args) {
          int counter;
          int n = 10;
          int sum = 0;
          for (counter=1; counter<=n; counter++) {
            sum = sum + counter;
          }
          System.out.println(sum);
        }
      }
    4. Print the sum of the odd numbers from 1 to n
       
      1. Using "if"
        class MyCode {
          public static void main(String[] args) {
            int counter;
            int n = 10;
            int sum = 0;
            for (counter=1; counter<=n; counter++) {
              if (counter % 2 != 0)
                sum = sum + counter;
            }
            System.out.println(sum);
          }
        }
      2. Using a different increment
        class MyCode {
          public static void main(String[] args) {
            int counter;
            int n = 10;
            int sum = 0;
            for (counter=1; counter<=n; counter+=2) {
              sum = sum + counter;
            }
            System.out.println(sum);
          }
        }
    5. Print the letters in a String
      class MyCode {
        public static void main(String[] args) {
          int i;  // i for index, rather than counter
          String s = "Carpe diem";
          for (i=0; i<s.length(); i++) {
            char c = s.charAt(i);
            System.out.println(c);
          }
        }
      }
    6. Print the letters in a String in reverse
      class MyCode {
        public static void main(String[] args) {
          int i;
          String s = "Carpe diem";
          for (i=s.length()-1; i>=0; i--) {
            char c = s.charAt(i);
            System.out.println(c);
          }
        }
      }
  2. Example:  isPrime
    (See code below)
     
  3. The "while" statement
     
    1. Division by Subtraction
      class MyCode {
        public static void main(String[] args) {
          int x = 35;
          int y = 5;
          int quotient = 0;
          while (x >= y) {
            x -= y;
            quotient++;
          }
          System.out.println(quotient);
        }
      }
    2. Another "while" Example
      class MyCode {
        public static void main(String[] args) {
          String s1 = "hi";
          String s2 = "bonjour";
          while (s1.length() < s2.length()) {
            s1 = s1 + "hi";
          }
          System.out.println(s1);
          System.out.println(s2);
        }
      }
  4. Example:  nthPrime
    (See code below)

     
  5. Sample code:  isPrime and nthPrime
    class IsPrimeAndNthPrimeExamples {
    
      //////////////////////////////////////////
      /// isPrime
      //////////////////////////////////////////
    
      // Returns true if n is a prime number, and false otherwise.
      // Do not worry about efficiency (yet).  We'll make this faster soon...
      public static boolean isPrime(int n) {
        int counter;
        if (n < 2) return false;
        for (counter=2; counter<n; counter++) {
          if (n % counter == 0)
            return false;
        }
        return true;
    
      }
    
      public static void testIsPrime() {
        System.out.print("Testing isPrime()... ");
        assert(isPrime(2));
        assert(isPrime(3));
        assert(!isPrime(4));
        assert(isPrime(5));
        assert(!isPrime(6));
        assert(isPrime(8179));
        assert(!isPrime(8211));
        assert(!isPrime(-3));
        assert(!isPrime(0));
        assert(!isPrime(1));
        System.out.println("Passed all tests!");
      }
    
      //////////////////////////////////////////
      /// nthPrime
      //////////////////////////////////////////
    
      // Returns the nth prime number, or -1 if n is non-positive.
      // Do not worry about efficiency (yet).  We'll make this faster soon...
      public static int nthPrime(int n) {
        int counter = 1;
        int numberOfPrimes = 0;
        if (n < 1) return -1;
        while (numberOfPrimes < n) {
          counter++;
          if (isPrime(counter))
            numberOfPrimes++;
        }
        return counter;
      }
    
      public static void testNthPrime() {
        System.out.print("Testing nthPrime()... ");
        assert(nthPrime(1) == 2);
        assert(nthPrime(2) == 3);
        assert(nthPrime(3) == 5);
        assert(nthPrime(4) == 7);
        assert(nthPrime(5) == 11);
        assert(nthPrime(6) == 13);
        assert(nthPrime(-5) == -1);
        assert(nthPrime(0) == -1);
        System.out.println("Passed all tests!");
      }
    
      //////////////////////////////////////////
      /// main
      //////////////////////////////////////////
    
      public static void main(String[] args) {
        testIsPrime();
        testNthPrime();
      }
    }
  6. Nested Loops
    class MyCode {
      public static void main(String[] args) {
        int x, y;
        for (x=1; x<=4; x++) {
            for (y=1; y<=4; y++)
                System.out.print("(x=" + x + ",y=" + y + ") ");
            System.out.println();
        }
      }
    }

    Output:

    (x=1,y=1) (x=1,y=2) (x=1,y=3) (x=1,y=4) 
    (x=2,y=1) (x=2,y=2) (x=2,y=3) (x=2,y=4) 
    (x=3,y=1) (x=3,y=2) (x=3,y=3) (x=3,y=4) 
    (x=4,y=1) (x=4,y=2) (x=4,y=3) (x=4,y=4) 
  7. Nested Loops in Graphics
    import java.awt.*;
    import javax.swing.*;
    
    class MyGraphics extends JComponent {
    
      public void paint(Graphics page) {
        int rows=5, cols=7;
        int row, col;
        for (row=0; row<rows; row++)
          for (col=0; col<cols; col++)
            paintCell(page, row, col, rows, cols);
      }
    
      // Helper method to paint a single cell in the 2d grid
      public void paintCell(Graphics page, int row, int col, int rows, int cols) {
        int width = getWidth();
        int height = getHeight();
        int left = col * width  / cols;
        int top  = row * height / rows; 
        int right  = (col+1) * width  / cols;
        int bottom = (row+1) * height / rows;
    
        // paint the grid's outline
        page.setColor(Color.black);
        page.drawRect(left, top, right-left, bottom-top);
    
        // fill the cell
        page.setColor(Color.blue);
        page.fillOval(left, top, right-left, bottom-top);
    
        // label the cell
        page.setColor(Color.black);
        page.setFont(new Font("Arial", Font.BOLD, 14));
        String label = row + "," + col;
        drawCenteredString(page, label, left, top, right-left, bottom-top);
      }
    
      // As with any "gray code", you should know how to USE this code but
      // you do not have to know how to WRITE it (that is, you may copy+paste
      // it into your code as needed).
      public void drawCenteredString(Graphics page, String s,
                                     int left, int top, int width, int height) {
        // Center text within the given rectangular bounds
        FontMetrics fm = page.getFontMetrics(page.getFont());
        int textX = left + (width - fm.stringWidth(s))/2;
        int textY = top + (height - fm.getHeight())/2 + fm.getAscent();
        page.drawString(s, textX, textY);
      }
      
      //////////////////////////////////////////////
      ///           END OF YOUR CODE             ///
      ///  (you may ignore all the code below!!! ///
      //////////////////////////////////////////////
    
      public Dimension getPreferredSize() {
        int initialWidth = 500;
        int initialHeight = 400;
        return new Dimension(initialWidth, initialHeight);
      }
    
      public static void main(String[] args) {
        JComponent jc = newInstance();
        JFrame frame = new JFrame(jc.getClass().getName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel cp = new JPanel();
        cp.setLayout(new BorderLayout());
        cp.add(jc);
        frame.setContentPane(cp);
        frame.pack();
        frame.setVisible(true);
      }
    
      // Returns an instance of this class as a JComponent.  This is necessary so
      // students can rename this class without changing the "main" method's body.
      public static JComponent newInstance() {
        StackTraceElement[] trace = null;
        try { throw new RuntimeException(); }
        catch (Exception e) { trace = e.getStackTrace(); }
        try { return (JComponent)Class.forName(trace[0].getClassName()).newInstance(); }
        catch (Exception e) { return null; }
      }
    }

    Output:


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