본문 바로가기
Program/C

11. C언어 switch 문

by Murciellago 2021. 10. 20.
반응형
SMALL

이 장에서는 C언어 프로그래밍에서 switch문을 만드는 방법을 설명하겟습니다

switch 문을 사용하면 많은 대안 중에서 하나의 코드로 실행할 수 있다

switch 문은 읽고 쓰기가 훨씬 쉽습니다

 

1. C언어 switch~case 문

     ex) switch 문

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
switch (expression)
​{
    case constant1:
      // statements
      break;
 
    case constant2:
      // statements
      break;
    .
    .
    .
    default:
      // default statements
}
cs

 

2. switch 문 작동방법

   - expression 함수에서 case 문에 해당하는 함수를 실행

   - 일치하는 항목이 있으면 일치하는 함수 명령문이 실행

   - 여러 case 문 중에 해당 constant2 값이 일치하면 case constant2가 실행 후 break 됨

   - 일치하는 항목이 없으면 switch 문에 default 값을 실행하고 종료됨

 

* break 문을 사용하지 않으면 해당 항목 실행 후 모든 명령문이 실행

* switch 문은 default는 선택사항임\

 

3. switch 문 순서도

 

     ex) 단순 계산기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <stdio.h>
 
int main() {
    char operator;
    double n1, n2;
 
    printf("Enter an operator (+, -, *, /): ");
    scanf("%c"&operator);
    printf("Enter two operands: ");
    scanf("%lf %lf",&n1, &n2);
 
    switch(operator)
    {
        case '+':
            printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
            break;
 
        case '-':
            printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
            break;
 
        case '*':
            printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
            break;
 
        case '/':
            printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
            break;
 
        // operator doesn't match any case constant +, -, *, /
        default:
            printf("Error! operator is not correct");
    }
 
    return 0;
}
 
 

 

     output) 

1
2
3
4
Enter an operator (+-*,): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1
 

 

* 사용자가 입력한 연산자와 두개의 정수를 입력하게 된다

* 연산자를 입력하면 switch문에 해당하는 case 문에서 할당된 코드를 실행시킨다

* 입력된 두개의 정수를 대입하여 계산하여 출력한다

* printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);

* break 문으로 switch 문은 종료된다

 

 

 

반응형
LIST

'Program > C' 카테고리의 다른 글

13. C언어 전처리기와 매크로  (0) 2021.11.17
12. C언어 goto 문  (0) 2021.10.20
10. C언어 break와 continue  (0) 2021.10.20
9. C언어 While 및 do~while 문  (0) 2021.10.18
8. C언어 for 문  (0) 2021.10.14

댓글