入れ子のif - else
CoddyのCジャーニー「基礎」セクションの一部。レッスン 31/63。
if-else文を互いに入れ子にできます。これにより、階層的な意思決定構造を作成できます。
例:
if (age > 18) {
if (hasLicense) {
printf("You can drive");
} else {
printf("Get a license first");
}
} else {
printf("Too young to drive");
}無限にネストできます:
if (condition1) {
if (condition2) {
if (condition3) {
// condition1、condition2、condition3がすべて真の場合
}
}
}波かっこがない場合、elseは、その上にある、まだelseが対応していない最も近いifに対応します。
if (age > 18)
if (hasLicense)
printf("You can drive");
else
printf("Get a license first");ここでは、インデントにかかわらず、elseはif (hasLicense)に対応します。対応関係を明確にするには、波かっこを使いましょう。
チャレンジ
簡単ジェットコースターに乗れるかどうかを判定するプログラムを作成しましょう。要件は次のとおりです。
- 12歳以上であること
- 身長が150cmを超えていること
- 両方の要件を満たしていても、15歳未満の場合は大人の付き添いが必要です
各ケースについて、次のメッセージを正確に出力してください。
- 年齢が低すぎる場合:
Sorry, you are too young - 身長が足りない場合:
Sorry, you are not tall enough - 15歳未満で大人がいない場合:
Sorry, you need an adult with you - 15歳未満で大人がいる場合:
You can ride with adult supervision! - 15歳以上で身長が足りている場合:
You can ride by yourself!
自分で試してみよう
#include <stdio.h>
int main() {
int age, height;
int hasAdult;
scanf("%d %d %d", &age, &height, &hasAdult); // この行は変更しないでください
// 以下にコードを書いてください
return 0;
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
基礎のすべてのレッスン
自分で練習してみよう: Cオンラインコンパイラ