Course C Initial 11st – Switch Commands


Switch is other way to selections commands, it test a variable integer or character, (it cans not use a float or double for example), with cases. See below its structure:


Read the image. A switch command is use when we have a finite number of possibilities. In C, we can use switch how many time we desire. Other point is which switch allows breaks in the code. So see below breaks being running.


As we can see, the case can use with breaks, since 1 to 7 for example. But it’s limited.
Note: in Switch Command, we can’t test conditions as in if-else, so the form case 2<4 is invalid to switch.
In case, never forget to put break; it’s the signal to the compiler that what’s inside case, had finished. In default, it’s not required.
Now, see an alternative structure to switch command:


That works, but it isn’t required. So I prefer use the previous way.
Note: Switch and If Else can be interconnected, but be careful with this.
In others words, we have a switch that test a variable with cases and one default if it be required. Break stop the run and log out of switch.
Now, Make the algorithm below, if it be hard, back in the beginner of this lesson or comment this post and I’ll answer you.
(Note: it’s the 5th Question of If-Else Command Exercise). Make an algorithm that reserves a number, an operator and other number, so calculates the operation solicited. For example: 7*2 is equal to 14, use an int, char and int respectively. Test what operation will be made and print the result.

So, look and learn.

Look for this algorithm and after make it in your compiler.


In this case, it was used a char, but could be an int, no other data type. If you have doubt, comment. In the next lesson, we’ll make algorithms with switch command.
Well, that’s all Folks!
See you later!

Comentários

More Famous Posts

Course C Initial 7th – Training with Math

Course C Initial – 3rd Variables Part. 1

Course Python For Life 3 – Input Command