Lecture 07 More Control

Joseph Haugh

University of New Mexico

Free Recall

  • Get out a sheet of paper or open a text editor
  • For 2 minutes write down whatever comes to mind about the last class
    • This could be topics you learned
    • Questions you had
    • Connections you made

Control so far

  • So far we have seen the following control structures:
    • if: allows for branching
    • while: allows for looping
  • You could theoretically do everything with just these two control structures
  • However, it is often nice to have specialized ones as well

Example: Validating Input

  • For example, let’s try to write a function which does the following:
    • Reads in input from the user
    • Converts it to a number
    • Makes sure that number is positive
    • Repeats this until the user gets it right
  • Our first attempt will be with a while loop

Example: Validating Input With While Loop

boolean isPositive(int n) {
    return n >= 0;
}

int validateUserInput() {
    String input = IO.readln("Enter a positive number: ");
    int n = Integer.parseInt(input);
    while (!isPositive(n)) {
        input = IO.readln("Enter a positive number: ");
        n = Integer.parseInt(input);
    }
    return n;
}

void main() {
    int n = validateUserInput();
    IO.println(n);
}

Example: Validating Input With While Loop

  • Works but we have to repeat ourselves
  • We have to repeat the lines to read and parse the input
  • Can it be improved?
boolean isPositive(int n) {
    return n >= 0;
}

int validateUserInput() {
    String input = IO.readln("Enter a positive number: ");
    int n = Integer.parseInt(input);
    while (!isPositive(n)) {
        input = IO.readln("Enter a positive number: ");
        n = Integer.parseInt(input);
    }
    return n;
}

void main() {
    int n = validateUserInput();
    IO.println(n);
}

While vs Do While

  • Of course!
  • We can use a do while loop instead
  • Recall, the semantics of a while loop
    • Check the condition
    • If it is true, do the body statements inside the loop
    • If it is false, continue past the loop
  • A do while loop has the following semantics:
    • Do the body statements inside the loop
    • Check the condition
    • If it is true, do the body statements inside the loop
    • If it is false, continue past the loop

Do While

  • Do while has the following syntax:

    do {
        <<bodyStatements>>
    } while (<<booleanCondition>>);
  • Do while is useful when you need the body of the loop to run first then check the condition

  • This is exactly what we need for our example!

Example: Validating Input With Do While Loop

boolean isPositive(int n) {
    return n >= 0;
}

int validateUserInput() {
    String input; // Is this necessary?
    int n;        // Or this? Why?
    do {
        input = IO.readln("Enter a positive number: ");
        n = Integer.parseInt(input);
    } while (!isPositive(n));
    return n;
}

void main() {
    int n = validateUserInput();
    IO.println(n);
}

Scoping

  • We had to declare input and n outside of the loop two different reasons
  • For input it is best to declare it outside to prevent creating a new version of input each time around the loop
  • For n we must declare it outside of the loop due to scope
  • The scope of a variable can broadly be understood as where in the code a variable can be referred to or seen
  • In Java the scope of a variable is bounded by the curly braces it was defined within
  • Therefore, if we defined n inside the loop then hit the closing curly brace of the loop n is no longer in scope and cannot be used

Example: Validating Input Scoping Problems

int validateUserInput() {
    do {
        // We could put input inside the loop without
        // error, but it would be suboptimal
        String input = IO.readln("Enter a positive number: ");
        int n = Integer.parseInt(input);
    } // n is out of scope after this curly brace
    // Thus, it cannot be seen in this condition!
    while (!isPositive(n));
    // Can also not be seen here!
    return n;
}
// Or here for that matter!

Common Looping Pattern

  • Many loops take on the following form:

    <<initStatements>>
    while (<<booleanCondition>>) {
        <<bodyStatements>>
        <<updateStatements>>
    }
  • For example, this loop we saw a few days ago has this form:

    int result = 0;  // Init statement
    int i = 1;       // Init statement
    while (i <= n) {
        result += i; // Body statement
        i++;         // Update statement
    }

For Loop

  • This pattern is so common there is a dedicated loop construct for it

  • Its called a for loop

  • Caution:

    • Java’s for loop is different than Python’s for loop
    • We will see later that Python’s is closer to Java’s foreach loop
  • For loop syntax:

    for (<<initStatement>>; <<booleanCondition>>; <<updateStatement>>) {
        <<bodyStatements>>
    }

For vs While

  • For example our previous while loop example:

    int result = 0;  // Init statement
    int i = 1;       // Init statement
    while (i <= n) {
        result += i; // Body statement
        i++;         // Update statement
    }
  • Could be rewritten with a for loop:

    int result = 0;
    for (int i = 1; i <= n; i++) {
        result += i;
    }

For vs While

  • While loops can do everything a for loop can
  • The choice of which to use should be made on per problem basis
  • Each have their niche