Understanding the Switch Statememt in C


A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

There are three critical components to the switch statement:

  • Case: This is the value that is evaluated for equivalence with the argument to the switch statement.
  • Default:This is an optional, catch-all expression, should none of the case statements evaluate to true.
  • Abrupt completion of the case statement; usually break: This is required to prevent the undesired evaluation of further case statements

Syntax:
     switch ( expression )
    {
    case 1 :
         // Block of Statement
         break;
    case 2 :
         // Block of Statement
         break;
    case 3 :
         // Block of Statement
         break;
     .
     .
     .
     default :
         // Block of Statement
         break;
    }

The above program is a simple example of how to use a switch statement in Java. The program prompts the user to enter a value, which is then stored in the variable "ch". The switch statement is then used to check the value of "ch" against a series of cases (1, 2, 3). If the value of "ch" matches any of the cases, the corresponding code block will be executed. If the value of "ch" does not match any of the cases, the code block for the default case will be executed. In this program, each case will print a different string based on the value entered by user. The break statement is used to exit the switch statement once a match is found and the corresponding code block is executed


Source Code

// Switch Statement
#include<stdio.h>
int main()
{
    int ch;
    printf("\nEnter The Value : ");
    scanf("%d",&ch);
    switch(ch)
    {
    case 1:
        printf("\n One");
        break;
    case 2:
        printf("\n Two");
        break;
    case 3:
        printf("\n Three");
        break;
    default:
        printf("\n Invalid No");
        break;
    }
    return 0;
}
 
To download raw file Click Here

Output

Enter The Value : 3
Three
Enter The Value : 6 Invalid No

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C