if STATEMENTS

1. What if...

Examine the following program. Predict the program’s output when the user inputs a value of 7. What will happen if the user enters a value other than 7? Check your predictions by running the program several times using different input values.

2. ...or else!

Study the following program and then run it several times, using a variety of positive and negative input values.

3. Your turn.

Write and test a program that states whether a user is old enough to view a particular movie. The program should prompt the user to input their age. If the user enters a value less than 13, make the program’s output state that they are not old enough to view the movie. Otherwise, the output should indicate that they are old enough to watch the movie.

4. Under pressure.

The elif (else if) keyword conveniently allows a single if statement to handle more than two possible outcomes. Examine the following program that provides feedback about the systolic blood pressure entered by the user. Then, run the program several times to trigger the three different possible outputs.

5. Pressure's on.

Edit the program above such that if the user enters a value from 120 up to (but not including) 130, the output states that the value is pre-high. The existing output messages for other values should remain the same.

6. A mathematical mystery.

Consider the following procedure:

Start with any positive integer and repeatedly apply the following rule:

  • If the number is even, divide it by 2.
  • If the number is odd, multiply it by 3 and add 1.

The famous Collatz Conjecture states that this process will always lead to a repeated 4-2-1 result, but it has yet to be proven! Experiment with running the following program to see how it shows each calculation step in the above procedure.
NOTE: This program uses the modulo operator, %, which gives the remainder when one number is divided by another. So, x%2 == 0 can be used to check if x is an even number (when x is divided by 2, the remainder is 0).

7. How many steps?

Edit the program above such that the output also tells the user how many times the calculation rule was applied to reach a value of 1.

Previous

while Loops

Next

if Statements