順次処理・分岐処理
c の分岐処理は if と switch
if
#include <stdio.h>
int main() {
int a;
printf("Please input an integer:");
scanf("%d", &a);
if (a > 0) {
printf("The input number is greater than 0.\n");
} else if (a == 0) {
printf("The input number is equal to 0.\n");
} else {
printf("The input number is less than 0.\n");
}
return 0;
}
scanf の & の意味。文字列をscanf関数で扱うとき
| 名称 | 構文 |
|---|---|
| 小なり | a < b |
| 小なりイコール | a <= b |
| 大なり | a > b |
| 大なりイコール | a >= b |
| 非等価 | a != b |
| 等価 | a == b |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int die_1;
int die_2;
int sum_dice;
printf("Rolling the dice...\n");
// random seed
srand((unsigned int) time(NULL));
die_1 = rand() % 6 + 1;
die_2 = rand() % 6 + 1;
printf("The number of eyes on the dice is %d and %d.\n", die_1, die_2);
sum_dice = die_1 + die_2;
if (sum_dice >= 2 && sum_dice <= 12) {
// if (sum_dice % 2 == 0) {
if (sum_dice == 2 || sum_dice == 4 || sum_dice == 6 ||
sum_dice == 8 || sum_dice == 10 || sum_dice == 12 ) {
printf("Even !!\n");
} else {
printf("Odds !!\n");
}
} else {
printf("Something wrong...\n");
}
return 0;
}
| 名称 | 構文 |
|---|---|
| 論理否定 | !a |
| 論理積 | a && b |
| 論理和 | a || b |
Switch
条件式を判定して多方向分岐を行う。
case で判定の対象となるのは、整数、文字定数、定数の式のみ。少数や条件式は使えない。
#include <stdio.h>
int main(void) {
int num;
printf("Please input number from 1 to 3: ");
scanf("%d", &num);
switch (num) {
case 1:
printf("! ONE !\n");
break;
case 2:
printf("!! TWO !!\n");
break;
case 3:
printf("!!! THREE !!!\n");
break;
default:
printf("orz_Wrong Number_orz\n");
break;
}
}