Lecture 10, CS 302-6, September 26

 

  1. Review
    1. Boolean operators

                                                               i.      De Morgan’s Law

                                                             ii.      String comparisons

    1. Input Validation
    2. While Loop
  1. Loop ground rules
    1. Reminder: if statements do something once.  While statements do something until the condition is met.  If loops don’t exist.
    2. Be careful to avoid infinite loops

                                                               i.      Apple - one infinite loop

                                                             ii.      XKCD – http://xkcd.com/140/

    1. Declare variables before loop, if you need to access them afterwards
    2. Off-by-one-errors

                                                               i.      Be careful with <=, < etc in conditions

    1. Example – BankAccount.java
  1. For loops
    1. Special case of a while loop
    2. For when you know exactly how many times you have to do something
    3. Differences from while loop:

                                                               i.      Count-controlled vs event controlled

                                                             ii.      Definite vs indefinite

    1. Structure:

For(int i=0;i<x;i++)

{

      body

}

    1. Details:

                                                               i.      For( initialization; condition; update)

                                                             ii.      i is only declared within the for loop

1.      So, if you try to use it after the for loop is over, java will crash

    1. Example - Factorial.java
  1. For loop – other uses/examples
    1. We can do more than just count up in for loops

                                                               i.      Can count down, count up by 2, etc. i--, i+=2, etc.

                                                             ii.      Note – if we define counter before initialize, we can use it afterwards

    1. So, we can use for loops to count up to a certain number – similarly, we can use them to traverse the characters in a string
    2. One use – reversing a string
    3. Example – Palindrome.java
  1. Do Loop
    1. Almost identical to a While loop.

                                                               i.      Doesn’t check condition before first iteration

                                                             ii.      Post-test instead of pre-test

do

{

}

while(condition);

  1. HW
    1. Read 4.4-4.5