What is Switch Statement in C with example ?

  • Switch statement is an alternative to if else ladder statement which allows us to execute multiple operations for different values.
  • We can define various statement in multiple cases for different values of single variable.

Rules for switch statement

  • Switch expression should be an integer or character data type.
  • Case value must be an integer or constant value.
  • We can use only case value inside the switch statement.
  • Break statement is not mandatory in switch. It is optional.
  • If a program does not find a break statement in switch expression, all the cases in the switch will be executed along with the matched case.

Syntax for switch statement

[pastacode lang=”c” manual=”switch(expression)%7B%20%20%20%20%0Acase%20value1%3A%20%20%20%20%0A%2F%2Fcode%20to%20be%20executed%3B%20%20%20%20%0Abreak%3B%20%20%2F%2Foptional%20%20%0Acase%20value2%3A%20%20%20%20%0A%2F%2Fcode%20to%20be%20executed%3B%20%20%20%20%0Abreak%3B%20%20%2F%2Foptional%20%20%0A……%20%20%20%20%0Adefault%3A%20%20%20%20%20%0Acode%20to%20be%20executed%20if%20all%20cases%20are%20not%20matched%3B%20%20%20%20%0A%7D%20%20%20%20%0A” message=”” highlight=”” provider=”manual”/]

Flow chart for switch

Sample Program

[pastacode lang=”c” manual=”%20%20%20%20%23include%3Cstdio.h%3E%0A%0A%20%20%20%20int%20main()%20%7B%0A%20%20%20%20%20%20int%20number%20%3D%200%3B%0A%20%20%20%20%20%20printf(%22enter%20a%20number%3A%22)%3B%0A%20%20%20%20%20%20scanf(%22%25d%22%2C%20%26%20number)%3B%0A%20%20%20%20%20%20switch%20(number)%20%7B%0A%20%20%20%20%20%20case%2010%3A%0A%20%20%20%20%20%20%20%20printf(%22number%20is%20equals%20to%2010%22)%3B%0A%20%20%20%20%20%20%20%20break%3B%0A%20%20%20%20%20%20case%2050%3A%0A%20%20%20%20%20%20%20%20printf(%22number%20is%20equal%20to%2050%22)%3B%0A%20%20%20%20%20%20%20%20break%3B%0A%20%20%20%20%20%20case%20100%3A%0A%20%20%20%20%20%20%20%20printf(%22number%20is%20equal%20to%20100%22)%3B%0A%20%20%20%20%20%20%20%20break%3B%0A%20%20%20%20%20%20default%3A%0A%20%20%20%20%20%20%20%20printf(%22number%20is%20not%20equal%20to%2010%2C%2050%20or%20100%22)%3B%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20return%200%3B%0A%20%20%20%20%7D” message=”” highlight=”” provider=”manual”/]

Output

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like