[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)
[/spoiler]
[spoiler title=”Lesson Source Code”]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
#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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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.