Driving Test

Line: Conditional Line
Easy Selection Learning Outcome One Walkthrough
Type: Walkthrough
You should have completed: Getting Numbers This topic leads to: Magic Numbers
Counting Up Again

Summary

In order to tackle most problems, it is necessary to sometimes do one thing, and sometimes do another (or nothing). This is selection. In this example, the user is asked for their age, and based on that age we select whether to tell them that they are legally old enough to take the driving test, or to tell them how many years they must wait.

Task

  1. Create a new console application
  2. Within "main" type in the following code
    Code Snippet
  3. Run the program and enter '18'
  4. Run the program and enter '14'

    Note that if the condition in the if statement does not evaluate to true, the next statement after the if, the message command, is ignored and execution proceeds to the next statement.

  5. Change the code to add two new lines as follows
    Code Snippet
  6. Run the program and enter '18'
  7. Run the program and enter '14'
  8. Run the program and enter '17'

    The program reports the user is unable to take the test at age 17. Why is this? We need to be very precise in our instructions within programs, 17 is not greater than 17, it is equal to it, therefore the condition is false.

  9. Modify the condition to be userAge >= 17 and try the three input values again
  10. Put the cursor anywhere in your code and press Ctrl+K, then Ctrl+D straight away

    This applies automatic formatting to your code, in particular applying tabbed indentation. You will see that the if and else statements now line up vertically, and the statements controlled by that selection are indented relative to them. This vertical alignment makes code a lot easier to read and understand and is very good programming practice.

Questions

  1. How would you modify the program for Nigeria, where the legal driving age is 18?
  2. How can you modifiy the program to calculate and tell the user how many years they have to wait to be eligible to drive? Will your solution be efficient and not perform the calculation if the user is old enough to drive? Hint: Find out what a 'block' of code is.