조건문
개요
조건에 의해 선별적인 실행이 가능한 문장
사례
- 단순 if : 단순 if : 시험 응시자 중 점수가 90점 이상인 경우만 “Excellent” 출력
- if ~ else : 시험 응시자 중 점수가 90점 이상이면 “pass” 그렇지 않으면 “fail” 출력
- 다중 if ~ else : 시험 응시자의 학점을 부여할 때 점수가
90점 이상이면 “A”, 80~89점이면 “B”, 그 외는 “F” 출력
활용
단순 if
시험 응시자 중 점수가 90점 이상인 경우만 “Excellent” 출력
#include <stdio.h>
int main(void)
{
int score;
printf("Enter your score: ");
scanf("%d", &score);
if (score >= 90)
printf("Excellent\n");
return 0;
}
if ~ else
시험 응시자 중 점수가 90점 이상이면 “pass” 그렇지 않으면 “fail” 출력
#include <stdio.h>
int main(void)
{
int score;
printf("Enter your score: ");
scanf("%d", &score);
if (score >= 90)
printf("pass\n");
else
printf("fail\n");
return 0;
}
다중 if ~ else
시험 응시자의 학점을 부여할 때 점수가 90점 이상이면 “A”, 80~89점이면 “B”, 그 외는 “F” 출력
#include <stdio.h>
int main(void)
{
int score;
printf("Enter your score: ");
scanf("%d", &score);
if (score >= 90)
printf("A\n");
else if (score >= 80)
printf("B\n");
else
printf("F\n");
return 0;
}
switch ~ case
시험 응시자의 학점을 부여할 때 점수가 90점 이상이면 “A”, 80
89점이면 “B”, 7079점이면 “C”, 그 외는 “F” 출력
#include <stdio.h>
int main(void)
{
int score;
printf("Enter your score: ");
scanf("%d", &score);
switch (score / 10)
{
case 10:
case 9:
printf("A\n");
break;
case 8:
printf("B\n");
break;
case 7:
printf("C\n");
break;
default:
printf("F\n");
}
return 0;
}