C Program#181 – To Understand switch Statement.

Program to Understand switch Statement:

Brief Intro. :

  • switch statement provides multiple ways to test a variable’s or expression’s value for equality.
  • Inside switch many cases may be defined with associated block, when a case matches that block executes.
  • Syntax : switch statement
  • switch,case,default & break are keywords.
  • switch expression or variable must be an integral type.(short,char,long,int).
  • case labels must be constants or constant expressions.
  • case labels must be unique.No two labels can have the same value.
  • case labels must be ended with colon (:)
  • break statement transfers the control out of switch statement.
  • break statement is optional and used when no further tests must be performed.
  • default is also optional, if present it will be executed when there is no matching case found.
  • There can be only one default.
  • default and other cases need not be in order, default may be placed anywhere but usually at the end.
  • whichever is last case, there is no need to use break.
  • switch may also be nested like other statements.
  • switch may replace if-elseif or ladder if but, only where test for equality, switch doesn’t permits relational or logical operators in case.
  • Still not understood ? See the proper working example in action below.

Full Well Commented, Self-Explanatory Example Program of the same given below.

Below Here are Three (3) different Outputs of the program.

Output of the Program (Run 1 ):

Output of the Program (Run 2 ):

Output of the Program (Run 3 ):

Output of the Program (Run 4 ):