Math Functions

Line: Conditional Line
Medium Selection Learning Outcome One Walkthrough
Type: Walkthrough
You should have completed: Ticket Sales This topic leads to: Try Parsing

Summary

If statements are one method of selecting which statements to execute, but another exists which is more appropriate where you have an input or variable that can be one of a fixed set of values, and want to do something different for each value. In this situation a switch statement is the syntax to use (also sometimes called a select or case statement).

Task

  1. Create a new console application
  2. Within "main" type in the following code

    Note that we do the minimum amount of unique work in the different cases within the switch statement, rather than typing out the full Console.WriteLine each time.
    Each case within the switch will execute if the variable in the switch statement matches that value exactly. The break keyword tells the computer to move to the end of the current block, in this case the end of the switch statement.

  3. Run the program and see what happens if you type in one of the four operations correctly.
  4. Run the program and try entering 'h' for the input requested. Why did this happen?

Questions

  1. There is a default: case which executes if none of the other cases match. Find out about this and add one to your program.
  2. How might you display a different, warning message if the user types in the wrong thing?