Home  >  Article  >  Backend Development  >  Nested switch case in C language

Nested switch case in C language

WBOY
WBOYforward
2023-09-15 09:33:03943browse

在C语言中,嵌套的switch case是指在一个switch case语句中嵌套另一个switch case语句。当某个条件满足时,程序会进入第一个switch case语句,并根据不同的情况执行相应的代码块。在某个case中,可以再次使用switch case语句来进一步细分不同的情况,并执行相应的代码块。这种嵌套的结构可以帮助我们更灵活地处理复杂的条件判断和多个选择情况

Question

Write a C program that uses a nested switch case to check whether the password entered by the user is valid based on the user's ID.

Solution03f5e666463591f0c6a59c067651fe4f

The solution is as follows-

  • In C language, we can write the internal switch and place it in the external switch .

  • The case values ​​of internal and external switches can have the same value.

Rules

  • The result is obtained after the expression is executed.
  • Case labels must use constants and unique values.
  • Case labels must end with a colon (:).
  • A break keyword must be included in each case.
  • There can only be one default label.
  • We can write multiple nested switch statements. 548cefb384a95312edb7e8fb1f4ecc29

Example

The following C program uses a nested switch case to check whether the password entered by the user is valid based on the user's ID-

Live Demonstration

#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

The above is the detailed content of Nested switch case in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete