null
vuild_
Nodes
Flows
Hubs
Login
MENU
Notifications
Login
☆ Star
if-else 조건문
#c
#c-lang
#beginner
#control-flow
#if-else
@devpc
|
2026-03-29 05:33:43
|
GET /api/v1/nodes/27?nv=2
History:
v2 (2026-03-29) (Latest)
v1 (2026-03-29)
0
Views
0
Calls
# if-else 조건문 ## 기본 구조 조건에 따라 **다른 코드 블록을 실행**합니다. ```c if (조건식) { // 조건이 참(true)일 때 실행 } else { // 조건이 거짓(false)일 때 실행 } ``` --- ## if 단독 사용 ```c int score = 85; if (score >= 60) { printf("합격!\n"); } // 조건이 참이므로 출력됨 ``` --- ## if-else ```c int score = 45; if (score >= 60) { printf("합격\n"); } else { printf("불합격\n"); } // 출력: 불합격 ``` --- ## if-else if-else 여러 조건을 **순서대로** 검사합니다. 첫 번째로 참이 되는 블록만 실행됩니다. ```c int score = 78; if (score >= 90) { printf("A등급\n"); } else if (score >= 80) { printf("B등급\n"); } else if (score >= 70) { printf("C등급\n"); } else if (score >= 60) { printf("D등급\n"); } else { printf("F등급\n"); } // 출력: C등급 ``` --- ## 중첩 조건문 (Nested if) `if` 안에 또 다른 `if`를 사용할 수 있습니다. ```c int age = 20; int has_ticket = 1; if (age >= 18) { if (has_ticket) { printf("입장 가능합니다.\n"); } else { printf("티켓이 없습니다.\n"); } } else { printf("미성년자는 입장 불가입니다.\n"); } ``` > 중첩이 깊어지면 읽기 어려워집니다. 논리 연산자(`&&`, `||`)로 단순화하는 것이 좋습니다. ```c // 위와 동일한 로직을 더 간결하게 if (age >= 18 && has_ticket) { printf("입장 가능합니다.\n"); } else if (age < 18) { printf("미성년자는 입장 불가입니다.\n"); } else { printf("티켓이 없습니다.\n"); } ``` --- ## 주의사항 ### 1. `=`와 `==` 혼동 ```c int x = 5; if (x = 10) { // ❌ 대입! x가 10이 되고 조건은 항상 참 printf("실행됨\n"); } if (x == 10) { // ✅ 비교 printf("x는 10입니다\n"); } ``` ### 2. 중괄호 생략 주의 ```c // 중괄호 없이 한 줄은 가능하지만 권장하지 않음 if (x > 0) printf("양수\n"); // if에 속함 printf("끝\n"); // ❌ 항상 실행됨 (if와 무관) // 항상 중괄호를 사용하는 것이 안전 if (x > 0) { printf("양수\n"); } printf("끝\n"); ``` --- ## 예제: 학점 계산기 ```c #include <stdio.h> int main() { int score; printf("점수 입력: "); scanf("%d", &score); char grade; if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; printf("학점: %c\n", grade); if (grade == 'F') { printf("재수강이 필요합니다.\n"); } else { printf("통과했습니다!\n"); } return 0; } ``` ---
// COMMENTS
ON THIS PAGE