### 制御文の記述
– if, for, whileなどの制御式を使う
– 制御式が条件を満たしていることをture, 満たしていないことをfalse
– 何もしない空文は ; と書く
### if文
int main(void){ int a = 10, b = 20, c; if (a == 10) printf("a is 10. \n"); if (a == b){ printf("a is equal to b. \n"); } else { printf("a is not equal to b. \n"); } if (b > 100) c = 1; else if (b > 50) c = 2; else if (b > 10) c = 3; else c = 9; printf("b=%d c=%d\n", b, c); return 0; }
$ ./dev
a is 10.
a is not equal to b.
b=20 c=3
### for
int main(void){ int i, sum, mul; sum = 0; mul = 1; for(i=1; i<=5; i++){ sum = sum + i; mul = mul * i; } printf("sum=%d mul=%d\n", sum, mul); for(i=40; i>=20; i=i-2){ printf("%d ", i); } printf("\n"); return 0; }
$ ./dev
sum=15 mul=120
40 38 36 34 32 30 28 26 24 22 20
### while
while(1)と書くと、breakを使わないと無限ループになる
int main(void){
int i=1;
while(i < 1000){
printf("%d ", i);
i = i * 2;
}
printf("\n");
return 0;
}
[/code]
$ ./dev
1 2 4 8 16 32 64 128 256 512
### do-while
do-whileは使用頻度が然程高くない
[code]
int main(void){
int n;
char a[80], b[] = "ABCD";
n = -1;
do {
++n;
a[n] = b[n];
} while(b[n] != '\0');
printf("a=%s b=%s\n", a, b);
return 0;
}
[/code]
$ ./dev
a=ABCD b=ABCD
### switch
[code]
int main(void){
int a;
for(a=1; a<=5; a++){
printf("-------%d\n", a);
switch(a){
case 1:
printf("a=1\n");
break;
case 3:
printf("a=3\n");
break;
case 5:
printf("a=5\n");
break;
default:
printf("others\n");
}
}
return 0;
}
[/code]
$ ./dev
-------1
a=1
-------2
others
-------3
a=3
-------4
others
-------5
a=5
### break & continue
[code]
int main(void){
int n;
printf("----- break test\n");
for (n=1; n<=3; n++){
printf("%d start\n", n);
if (n == 2) break;
printf("%d end\n", n);
}
printf("----- continue test\n");
for (n=1; n<=3; n++){
printf("%d start\n", n);
if (n == 2) continue;
printf("%d end\n", n);
}
return 0;
}
[/code]
$ ./dev
----- break test
1 start
1 end
2 start
----- continue test
1 start
1 end
2 start
3 start
3 end
意図的に無限ループを指定できるってのは面白いです。