On this mastery I’ll show you what and how to use the conditional switch in C++.
Switch is a statement that tests a variable for equality in a list of given conditions. It is somehow a summarized version of IF when you have a lot of conditions.
This flow chart may help you understand better, and this webpage too:
The default syntax of switch goes like this:
switch (expression) case “condition” : outcome [default:statement] //This is used when the variable input isn’t a valid option.
So, for the purpose of this mastery, lets create a program were the user can input his points on masteries so far and tell him if his good or screwed. Do as follows:
- Create our “basic” program.
- Inside the int, declare a char variable with an assigned value.
- Use switch to condition the outcome and tell the user if his good or screwed.
Your program should look something like this:
Now let’s test it:
Let’s just play with another value:
Great! Now you know what and how to use switch conditional.
Mastery 17 by Omar Peza is licensed under a Creative Commons Attribution 4.0 International License.