Home  >  Article  >  Backend Development  >  How to use switch case statement in c language

How to use switch case statement in c language

angryTom
angryTomOriginal
2020-02-28 17:43:0014572browse

How to use switch case statement in c language

How to use the switch case statement in c language

C language provides a switch statement for multi-branch selection, its general form is :

switch(表达式){ 
    case 常量表达式1:  语句1;
    case 常量表达式2:  语句2;
    … 
    case 常量表达式n:  语句n;
    default:  语句n+1;
}

The semantics are: calculate the value of the expression. And compare it with the subsequent constant expression values ​​one by one. When the value of the expression is equal to the value of a certain constant expression, the subsequent statements will be executed, and then no judgment will be made, and all subsequent statements after the case will continue to be executed. If the value of the expression is different from the constant expressions after all cases, the statement after default will be executed.

Recommended learning: c language video tutorial

Example:

#include <stdio.h>
int main(void){
    int a;
    printf("input integer number:    ");
    scanf("%d",&a);
    switch (a){
        case 1:printf("Monday\n");  break;
        case 2:printf("Tuesday\n");   break;
        case 3:printf("Wednesday\n");  break;
        case 4:printf("Thursday\n");  break;
        case 5:printf("Friday\n");  break;
        case 6:printf("Saturday\n");  break;
        case 7:printf("Sunday\n");  break;
        default:printf("error\n");
    }
    return 0;
}

Program interpretation:

This program requires inputting a number and outputs the English word for the week it corresponds to.

Notes:

1. The values ​​of each constant expression after the case cannot be the same, otherwise an error will occur.

2. After case, multiple statements are allowed and do not need to be enclosed in {}.

3. The order of each case and default clause can be changed without affecting the program execution result.

4. The default clause can be omitted.

PHP Chinese website, a large number of programming learning courses, welcome to learn!

The above is the detailed content of How to use switch case statement in c language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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