Making Decisions

So far, every program we've written has followed the statements in program order, executing them one by one from top to bottom, every time without change. One of the powers of algorithms, however, comes from their ability to construct computations that may include or omit certain steps - in other words, make decisions about the next statements to be executed, based on the provided inputs or current algorithm state.

The If Statement

The if statement is the most basic type of conditional statement. It alters the flow of execution of the program based on the true or false value of a specified condition.

Statement Syntax

The basic structure of the if statement is as follows:

if condition {
    # block of statements executed when condition is true
}
else {
    # block of statements executed when condition is false
}

In this definition,

  • the condition must be a Boolean value or expression (for example, the result of a comparison).
  • the sequence of statements between the opening and closing braces {...} is called a block.

When the condition is met (its value is true), the statements in the first (if) block are executed. On the other hand, when the condition value is false, the statements in the second (else) block (marked by the else keyword) are executed.

The else part is optional and can be omitted, in which case the if statement does nothing if the condition is not met:

if answer == 42 {
    print "Found it!"
}
# ... else do nothing

Let's look at an example.

Odds and Evens

Suppose we wanted to write a simple program that, provided a number, would output "even" if the number is divisible by 2, and "odd" if it is not. We can express this using the if keyword, like so:

console

Using remainders

To refresh our memories, % is the very handy remainder operator, and if the remainder is 0, i.e. a % b == 0, then a is divisible by b. Experiment with a few different numbers – for example, see what happens when you give it a negative number or a decimal fraction 🤔

Nested if and else

It is possible to nest multiple if-else statements inside one another, for example:

if N % 2 == 0 {
    if N % 3 == 0 {
        print "divisible by 2 and 3"
    }
    else {
        print "divisible by 2 but not by 3"
    }
}
else {
    print "not divisible by 2"
}

else if

We can check for multiple mutually exclusive conditions (meaning only one of them will hold true) by using an else if variation:

if condition1 {
    # condition 1 block
}
else if condition2 {
    # condition 2 block
}
# ...
else if conditionN {
    # condition N block
}
else {
    # else block
}

In this case, the conditions will be evaluated one by one, until the first condition whose value is true, in which case the corresponding else if block will be executed. If none of the conditions are true (all are false), then the else block is executed, if provided.

For example:

console

Important

Keep in mind that, strictly speaking, the conditions in an if-else if-else statement are not required to be mutually exclusive. This means that more than one of these conditions can be true. However, since they are evaluated in program order from top to bottom, the very first condition that matches will trigger the execution of the corresponding else if block, and the rest of the statements will never be evaluated at all.

Exercises

Absolute Value

Write a program that would ask the user for any number x, and then print the absolute value of this number:

  • If the number is positive or 0, the absolute value is the number itself (x)
  • Otherwise, the absolute value is the number opposite to this number (-x)

console

Sign

Modify the program above so that, in addition to the absolute value, it would also output the sign function of the number:

  • -1 if x < 0
  • 0 if x = 0
  • 1 if x > 0

Letter Grades

Students are assigned their final letter grades according to their class averages, according to the following rules:

  • A: >90%
  • B: 80-90%
  • C: 70-80%
  • D: 60-70%
  • F: <60%

Write a program that will prompt the student for his or her grade average between 0 and 100 and print the final letter grade for the student based on the average.

console

Quadrants

Recall the definition of quadrants from geometry:

        ^ Y
        |
     2  |  1
        |
  ------------> X
        |
     3  |  4
        |

A point is said to lie in the first quadrant if both X and Y coordinates are positive, in the second quadrant if X is negative and Y is positive, and so on (refer to the diagram above).

Write a program that will prompt the user for the coordinates X and Y, and print the number of the quadrant the corresponding point lies in.

console

FizzBuzz

Write a program that will prompt the user for a number, and do one of the following:

  • If the number is divisible by 3, then print "Fizz"
  • If the number is divisible by 5, then print "Buzz"
  • However, if the number is divisible by both 3 and 5, then print "FizzBuzz"
  • Lastly, if the number is divisible by neither 3, nor 5, then print the number itself

console

Back (030-comparisons)
Forward (045-going-in-loops)