Explain nested switch case in C language

CServer Side ProgrammingProgramming

Problem

Write a C program to check the entered password by the user is valid or not based on his/her ID using nested switch case.

Solution

The solution is explained below −

  • In C language, we can write inner switch which is placed in an outer switch.

  • The case values of the inner and outer switch can have common values.

Rules

  • An expression executes to a result.
  • Constants and unique values must be used for case labels.
  • Case labels has to be end with a colon ( : ).
  • A break keyword has to be included in each case.
  • There can be only one default label.
  • We can write nested multiple switch statements.

Example

Following is the C program to check the entered password by the user is valid or not based on his/her ID using nested switch case −

 Live Demo

#include <stdio.h>
int main(){
   int userid;
   int pwd;
   printf("enter userid:
");    scanf("%d",&userid);    switch (userid){       case 1234:          printf("enter password:
");          scanf("%d", & pwd);       switch (pwd){          case 0000:             printf("Tutorials Point
");          break;             default:          printf("incorrect password");             break;       }       break;          default:       printf("incorrect userid");          break;    } }

Output

You will see the following output −

Run 1:enter userid:
1234
enter password:
0000
Tutorials Point
Run 2:
enter userid:
1234
enter password:
234
incorrect password
raja
Updated on 15-Mar-2021 14:59:55

Advertisements