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

Nested switch case in C language

WBOY
Release: 2023-09-15 09:39:28
forward
977 people have browsed it

在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.

Solution< /h2>

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. < /li>

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;
   }
}
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template