if(조건문) {
if(조건문) 실행문;
}
- 중첩은 15단계까지 허용한다.(ANSI 표준 컴파일러)
if문이 다른 if나 else의 목표문이 될때.
if(조건식)문장
else
if(조건식)문장
else
if(조건식)문장
.
.
.
else 문장
//참인 조건식을 만날때까지 조건 검사.
//모든 조건식이 거짓이면 마지막 else 문장이 실행된다.
//마지막 else 문장이 없으면 아무것도 실행하지 않는다.
//일치되는 문자를 만나면 남은 if문을 건너뛸 수 있다.
//불필요한 연산에 시간을 낭비하지 않는다.
p.107_1
#include <stdio.h>
int main(void)
{
int a,b;
char ch;
printf("Do you wantto:\n");
printf("Add, Suvtract, Muktiply, or Divide?\n");
printf("Enter first letter:");
ch = getchar();
printf("\n");
printf("Enter first number:");
scanf("%d", &a);
printf("Enter second number:");
scanf("%d", &b);
if(ch=='A') printf("%d", a+b);
else if(ch=='S') printf("%d", a-b);
else if(ch=='M') printf("%d", a*b);
else if(ch=='D' && b!=0) printf("%d", a/b);
return 0;
}
p.107_2
#include <stdio.h>
int main(void)
{
int answer, count;
for(count=1; count<11; count++) {
printf("What is %d+%d?", count, count);
scanf("%d", &answer);
if(answer == count+count) printf("Right");
else {
printf("Sorry, you're wrong\n");
printf("Try again.\n");
printf("\nWhat is %d + %d?", count, count);
scanf("%d", &answer);
if(answer == count+count) printf("Right\n");
else
printf("Wrong, the answer is %d\n", count+count);
}
}
return 0;
}
p.108_2
#include <stdio.h>
int main(void)
{
float a, b;
int c;
printf("1:원의 넓이, 2:사각형의 넓이, 3:삼각형의 넓이\n");
printf("어떤 것의 넓이를 구할 것인지 선택하세요.:");
scanf("%d", &c);
if(c == 1) {
printf("반지름을 입력 : ");
scanf("%f", &a);
printf("\n원의 넓이는 %.2f입니다.", (a*a)*3.14);
}
else if(c == 2) {
printf("가로입력 :");
scanf("%f", &a);
printf("세로입력 :");
scanf("%f", &b);
printf("\n사각형의 넓이는 %.2f입니다.", a*b);
}
else if(c == 3) {
printf("밑변입력:");
scanf("%f", &a);
printf("높이입력:");
scanf("%f", &b);
printf("\n삼각형의 넓이는 %.2f입니다.", (a*b)/2);
}
return 0;
}