>> SPEAKER 1: The last time we analyzed integers, recall that we used some
Boolean expressions to check if a user's input n was between numbers
like 0 and 3, 4 and 7, and 8 and 10.
Well, we did that using if's and else if's, but it turns out you can
implement that same logic using a different programming construct
altogether while still achieving precisely the same result.
In fact, we can introduce something called a switch that allows us to
switch our behavior depending on the value of some variable.
>> Let's give this a try.
To do this, I'm first going to include the cs50 library by way of cs50.h.
I'm also going to include the standard library by way of standard I/O.h.
And I'm going to declare main in the usual way, int main void.
Open curly brace.
Close curly brace.
And now I'm going to ask the user for an integer.
>> Printf, give me an int between 1 and 10.
And now I'm going to get that int using the cs50
libraries function, GetInt.
Int, let's call it n, equals GetInt.
And now I'm going to do a bit of analysis on that integer.
Somewhat arbitrarily, but with this new construct known as a switch.
Switch on the value of n as follows.
>> In the case that n equals 1, or in the case that n equals 2, or in the case
that n equals 3, go ahead and execute this line of code.
Printf you picked a small int, break.
Now, I need to implement the equivalent of an ELT simple by
enumerating some additional cases.
>> In the case that n equals 4, or in the case that n equals 5, or in the case
that n equals 6, or in the case that n equals 7, go ahead and print out you
picked a medium Int.
Break.
Now in the case the user picked a large number, let's
detect that as follows.
>> In the case that the user picked eight or in the case that the user pick
nine, or in the case that the user pick 10, go ahead and print out you
picked a large Int.
Break.
ELT, if a user did not pick a number that falls into any of these 10 cases,
let's have some default behavior.
Which in this case will be as follows.
>> Default, Printf, you picked an invalid Int.
Break.
Now, if I save this file compile it with make switch.
Run it with .slash switch.
Let's do a couple of sanity checks.
I'll pick an Int of 1.
And ID picked a small int.
>> Let's now do .slash switch.
And type in say, negative 1.
And ID picked an invalid int.
At the end of the day, the switch construct does not enable you to do
anything that you couldn't already do with the more familiar if, else if,
else construct.
But if you have a finite list of values that you're checking for, a
switch statement may very well make your code more
explicit, or more readable.