C nested switch statements


  • We can use one switch-case statement inside the other switch-case statement.
  • The inner and outer switch() case constant may be same.
  • The basic syntax of nested switch-case statement is as follows:
  • Syntax

    switch(expression1)

    {

    case constant A:

    statements;

    switch(expression2)

    {

    case constant A:

    statements;

    break;

    case constant B:

    statements;

    break;

    default:

    statements;

    break;

    }

    break;

    case constant B:

    statements;

    break;

    default:

    statements;

    break;

    }
  • Here is an example of nested switch-case statement as follows:

Example

#include<stdio.h>

#include<conio.h>

int main()

{

int choice1,choice2;

printf("\n Enter your first choice:");

scanf("%d",&choice1);

switch(choice1)

{

case 1:

printf("\nOuter switch-case statement:Your first choice is 1");

printf("\n Enter your second choice:");

scanf("%d",&choice2);

switch(choice2)

{

case 1:

printf("\nInner switch-case statement:Your second choice is 1");

break;

case 2:

printf("\nInner switch-case statement:Your second choice is 2");

break;

case 3:

printf("\nInner switch-case statement:Your second choice is 3");

break;

default:

printf("\nNo match found");

break;

}

break;

case 2:

printf("\nOuter switch-case statement:Your first choice is 2");

break;

case 3:

printf("\nOuter switch-case statement:Your first choice is 3");

break;

default:

printf("\nNo match found");

break;

}

getch();

return 0;

}

Output

The output of the above program is as follows:

Enter your first choice: 1

Outer switch-case statement:Your first choice is 1

Enter your second choice:2

Inner switch-case statement:Your second choice is 2