Lecture 06 If While

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

Top to bottom program

  • In the simplest programs control or which statement goes next is very simple
  • The first statement goes first then control moves to the next line and then the next line and so on
  • For example:
void main() {
    int x = 3;         // First
    int y = 5;         // Second
    IO.println(x + y); // Third
}

Limitations

  • You can quickly see this type of control severely limits what we can do
  • How do we make branching decisions?
  • How can we repeat some statements over and over?

Control Flow: Branching

  • We can solve the problem of not being able to branch by utilizing if statements
  • if statements allow us to make decisions in our code
  • For example:
int abs(int n) {
    if (n < 0) {
        return n * -1;
    }
    return n;
}

void main() {
    IO.println(abs(3));
    IO.println(abs(-4));
}

If Syntax

  • If statements have the following syntax:

    if (<<booleanExpression>>) {
        <<thenStatements>>
    }

Else

  • If’s can also optionally have an else branch
  • The else branch is executed only when the if’s condition is False
  • For example:
// 2 < 0 is false
if (2 < 0) {
    IO.println("In the then branch");
}
// So the else branch is taken
else {
    IO.println("In the else branch");
}

Else if

  • Lastly, you can chain if and else to create mutually exclusive choices
  • This means only one branch in the chain will ever be taken
  • For example:
String toLetter(int grade) {
    if (grade <= 59) {
        return "F";
    } else if (grade <= 69) {
        return "D";
    } else if (grade <= 79) {
        return "C";
    } else if (grade <= 89) {
        return "B";
    } else {
        return "A";
    }
}
void main() {
    IO.println(toLetter(67)); // D
    IO.println(toLetter(91)); // A
    IO.println(toLetter(84)); // B
}

Nesting Ifs

  • You can also have ifs inside of other ifs!
  • For example:
boolean validateNumber(int n) {
    // Make sure the number is positive
    if (n > 0) {
        // Also make sure it is even
        if (n % 2 == 0) {
            // And that is larger than 100
            if (n > 100) {
                // Then it is validated
                return true;
            }
        }
    }
    return false;
}

Improving Nested Ifs

  • Often nesting ifs is unnecessary and can cause right creep
  • Right creep is the tendency of code to get more and more nested which in turn makes it more and more indented to the right
  • How can we alleviate this?
  • We can use &&!

Improving Nested Ifs

This code:

boolean validateNumber(int n) {
    // Make sure the number is positive
    if (n > 0) {
        // Also make sure it is even
        if (n % 2 == 0) {
            // And that is larger than 100
            if (n > 100) {
                // Then it is validated
                return true;
            }
        }
    }
    return false;
}

Improving Nested Ifs

Becomes:

boolean validateNumber(int n) {
    // Make sure the number is positive
    // AND even
    // AND greater than 100
    if (n > 0 && n % 2 == 0 && n > 100) {
        return true;
    }
    return false;
}

Further Improvements

What other improvements could be made?

boolean validateNumber(int n) {
    // Make sure the number is positive
    // AND even
    // AND greater than 100
    if (n > 0 && n % 2 == 0 && n > 100) {
        return true;
    }
    return false;
}

Further Improvements

We could remove the redundant n > 0 check

boolean validateNumber(int n) {
    // Make sure the number is even
    // AND greater than 100
    if (n % 2 == 0 && n > 100) {
        return true;
    }
    return false;
}

Common Pattern: Check Boolean Return Boolean

  • You will often be tempted to write code such as this:

    if (someCondition) {
        return true;
    }
    return false;
  • This is redundant as you are checking the condition (someCondition)

  • Then if it is true you return true

  • Otherwise, you return false

  • Well why not just return the condition?!

    return someCondition;

Further Improvements

Can we apply the check boolean return boolean rule here?

boolean validateNumber(int n) {
    // Make sure the number is even
    // AND greater than 100
    if (n % 2 == 0 && n > 100) {
        return true;
    }
    return false;
}

Further Improvements

Yes!

boolean validateNumber(int n) {
    // Make sure the number is even
    // AND greater than 100
    return n % 2 == 0 && n > 100;
}

Repeating Tasks

  • You should have encountered loops before
  • They allow the program to repeat a set of statements many times
  • For example:
int i = 0;
// Do loop body while
// i is less than 10
while (i < 10) {
    IO.println(i);
    i += 1;
}

While Loops

  • while loops repeat their body statements while their condition is true
  • while loops have the following syntax:
while (<<booleanCondition>>) {
    <<<bodyStatements>>>
}

Countdown

  • Let’s write a function to countdown from the given number to 0
void countdown(int n) {
    int i = n;
    while (i >= 0) {
        IO.println(i);
        i -= 1;
    }
}
void main() {
    countdown(10);
    countdown(0);
    countdown(-7);
}