Switch case statement

Switch case is useful where we have to select a choice between n numbers of alternatives. It is like if-else-if ladder statement.

Switch Syntax:

switch (variable)
{
    case value1:
        statement 1;
        statement 2;
    break;
	
    case value2:
        statement 1;
        statement 2;
    break;
	
    default:
        statement 1;
        statement 2;
}

Rules for writting switch statement in C language:

  1. The switch expression and case value must be of integral or character data type only, it cannot be real data type .
  2. The break statement in switch case is not must, it is optional. If there is no break statement found, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.
  3. When user gives some choice the switch statement takes the control to the specified case. If no such case exists, then control goes to default.

Valid/In-Valid Switch syntax:

Some valid switch syntax:

int x=5, y=10;
switch(x)
switch(x>y)
switch(x+y-2)

Some invalid switch syntax:

float f=10.0f, g=20.2f ;
switch(f)
switch(f+g)
switch(f+2.5)

Some valid case syntax:

case 3:
case 1+2:
case 'a':
case 'a'>'b':

Some invalid case syntax:

case 2.5:
case x: //character value in single quotes
case x+2:
case 1,2,3:

Example: Switch

Example 1: WAP to explain the use of fall through statement in switch case. 1

#include<stdio.h>
void main()
{
   int n;
   printf("Enter number: (1-5) ");
   scanf("%d",&n);
   switch(n)
   {
      case 1:
         printf("\nNumber is equal to 1.");
      case 2:
         printf("\nNumber is equal to 2.");
      case 3:
         printf("\nNumber is equal to 3.");
      case 4:
         printf("\nNumber is equal to 4.");
      case 5:
         printf("\nNumber is equal to 5.");
      default:
         printf("\nInvalid Input");
   }
}
Output 1:
Enter number: 4
Number is equal to 4.
Number is equal to 5.
Invalid Input

Output 2:
Enter number: 1
Number is equal to 1.
Number is equal to 2.
Number is equal to 3.
Number is equal to 4.
Number is equal to 5.
Invalid Input

Above program is an example of fall through statement. Re-write the above program and apply break keyword at end of each case.

switch(n)
{
    case 1:
        printf("\nNumber is equal to 1.");
    break;
    case 2:
        printf("\nNumber is equal to 2.");
    break;
    case 3:
        printf("\nNumber is equal to 3.");
    break;
    case 4:
        printf("\nNumber is equal to 4.");
    break;
    case 5:
        printf("\nNumber is equal to 5.");
    break;
}
Output 1:
Enter number: 4
Number is equal to 4.

Output 2:
Enter number: 1
Number is equal to 1.
Advertisement