switch … case statement usage

When the case is greater than or equal to 4, use switch … case statement

switch (expression)
  case constant 1 : statement body 1 ;
   case constant 2 : statement body 2 ;
   case constant 3 : statement body 3 ;
   case constant 4 : statement body 4 ;
  default : statement body;

The execution process of switch … case statement: 1. Compare the [expression]
to be discussed with the constant behind the case, and after finding a match, enter from this position and do all the statements below it. 2. The constants behind the case cannot be repeated . 3. You can add a break statement after each case statement, so as to ensure that only the matching item is done. 4. The essence of break: in the switch…case statement, the first break encountered will end the statement from that position. 5. You can add a default statement below the last case to indicate that if no match is found, then Do the item corresponding to default. 6. Default is not necessary. If break is encountered before, default will not be executed. If no break is encountered, it will be executed[]

  1. You can do nothing after the case, indicating the relationship with the next case.

The switch parameter type
  can be: byte short int long bool
  cannot be: float double (this floating point type cannot be compared exactly, so it cannot be) string
  But in c++11, string can be used as the condition of switch.

  char ch1='a',ch2='b';
    case 'a' :printf("0");
    case 'b' :
           case 'c' : printf("1");break;
           case 'd' : printf("2"); break;
           default : printf("3"); break;
   case 'c' :pritf("5");

Answer: 0345

void  main ()
     int score;
     char degree;
     printf ( "Please enter the score" );

    if(score<0 || score>100)
       printf ( "The entered number is invalid" );

            case 10:
            case 9 : degree='A'; break;
            case 8 : degree='B'; break;
            case 7 : degree='C'; break;
            case 6 : degree='D'; break;
            default : degree='E'; break;

Format: character variable=getchar();
char ch1;
putchar(); to output characters
putchar(character variable);
Let the user input an English letter. If it is uppercase it becomes lowercase, if it is uppercase it becomes lowercase.
Algorithm analysis:
1. Define a variable to store the character entered by the user,
2. Discuss the character

output the result of the operation

char ch ;
 printf ( "Please enter an English letter" );
if(ch>='a' && ch<='z')
if(ch>='A' && ch<='Z')

Leave a Comment

Your email address will not be published. Required fields are marked *