Switch Case in C Programming

“switch case ” is a case control structure.

 It contains case and default values.

“switch” statement takes a value as a expression for equality testing against a list of values/case.

Switch case statement is used in programming to select one amont multiple options.

syntax for a switch statement:-

Rules of switch statement −

In a “switch” statement we can have any number of case.

for equality testing against a list of values/case, constant-expression for a case must be the same data type as the variable in the switch expression.

When “switch” expression value is equal to a case, the statements following that case will execute until a break statement is reached/executes.

When a break statement is reached/executes, the switch statement terminates, and the control jumps to the outside of switch.

break is a optional. If there is no break in the switch case, the flow of control will jump to the next case of switch until a break is reached.

switch statement also have a default case, which appear at the end of the switch. when none of the cases is true  then default case will execute.

No break is needed in the default case. “default” case is also an optional.

Example: Write a program to take one numbers from user between 1 to 3. Write entered number in words if number between 1 to 3 otherwise print wrong number using switch.

OUTPUT

Note: In the above program, for example user enters a number 6 then output will be as follows:

Example: Write a program using switch statement but without break.  

OUTPUT

Description: Because if there is no break in the switch case, the flow of control will jump to the next case of switch until a break is reached.

Note: In the above program, for example value of char variable c = ‘ A’ then the output will be as follows:

Nested switch case

In C programming language we can define switch statement within another switch.

Syntax for a nested switch statement: −

Read More

  1. C++ program for student details
  2. Anonymous Object in C++
  3. Lowercase character to uppercase character
  4. Command Line Argument
  5. Local vs Global Object in C++
  6. Local and Nested Classes in C++
  7. Arithmetic operations using switch case
  8. Constructor in C++
  9. Know more about C++