[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)
[/spoiler]
[spoiler title=”Lesson Source Code”]
#include
#include
using namespace std;
int main(){
//Switch Statements to build a calculator
int choice = 0;
char operation = ' ';
double firstNum = 0.0, secondNum = 0.0, outcome = 0.0;
cout << "Enter a Value: ";
cin >> firstNum;
cout << "Enter a Second Value: ";
cin >> secondNum;
cout << "Select an option: 1 for +, 2 for -, 3 for *, 4 for /: ";
cin >> choice;
switch (choice){
case 1:{
outcome = firstNum + secondNum;
operation = '+';
break;
}
case 2:{
outcome = firstNum - secondNum;
operation = '-';
break;
}
case 3:{
outcome = firstNum * secondNum;
operation = '*';
break;
}
case 4:{
outcome = firstNum / secondNum;
operation = '/';
break;
}
default:{
cout << "\nYou've ruined EVERYTHING!!!!" << endl;
break;
}
}
//The value of 7 + 12 = 19
cout << "The value of: " << firstNum << " " << operation << " " << secondNum << " = " << outcome;
cout << endl;
system("PAUSE");
return 0;
}
[/spoiler]
Homework: None
Switch Statements
This is the first lesson where we touch on switch statements. If you take a look at them, they work almost exactly the same as an if statement. The only major difference between them is the absolute necessity to use break. Otherwise you can use the same bracket structure (though it’s not required in the cases inside of a switch, I prefer it for readability), and the same flow of logic.
Here’s an example of an if and a switch doing the same thing.
switch(x){
case 1:{
x += 5;
break;
}
case 2:{
x += 10;
break;
}
default:{
x += 1;
break;
}
//Note- The { } brackets can be dropped from these if's since they're 1-liners if you really want.
if( x == 1) { x += 5; }
else if(x == 2){ x += 10; }
else { x += 1; }
}
In general I find it easier to avoid switch statements in C++, but some people do feel as though they are used well for menus and things of that nature. It’s also more readable to most people that case is the result of a choice of a value, rather than an arbitrary test (which is what an if portrays). This is the other advantage of switch statements. They are almost always tied to user choices.