Lecture 10, CS 302-7 and 8, February 13

 

  1. Reminders
    1. Office hours – 4-5
    2. Program 1

                                                               i.      Due February 24

  1. Review
    1. Boolean operators

                                                               i.      De Morgan’s Law

    1. Basic Input Validation
    2. While Loop
  1. General loop guidelines
    1. Reminder: if statements do something once.  While statements do something until the condition is met.  No if loop!
    2. Be careful to avoid infinite loops
    3. Declare variables outside of loop (before)

                                                               i.      This will help avoid scope issues

    1. Off-by-one-errors

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

    1. Example – AreWeThereYet.java
  1. For loops
    1. Really just one 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(<initialization>;<condition>;<update>)

{

      //body

}

    1. Details:

                                                               i.      Three expressions: initialization, condition, update

                                                             ii.      Body is executed between the condition and update

                                                            iii.      The variable that we initialize in the <initialization> step is only declared within the for loop

1.      So, we can’t do:

for(int a=0;a<10;a++) {

      //Do something

                                          }

                                          S.o.p(a);

    1. Example - Factorial.java
  1. For loop – more complex example
    1. We can do more than just count up in for loops, update

                                                               i.      Can count down, count up by 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. Helpful string methods

                                                               i.      string.toUpperCase()

                                                             ii.      string.substring(start, end)

                                                            iii.      string.charAt(index)

                                                           iv.      string.length()

  1. HW
    1. Read 4.4