if文
March 9, 2020 · View on GitHub
if文
if文は、プログラミングにおける条件を記述する文であり、trueの場合は指定のブロック内のコードを実行します。以下はVにおけるif文の一般的なコード例です。
john_height := 100
maria_height := 178
if john_height < maria_height {
println("Maria is taller than John")
}
上のコードのprintln()は、条件がtrueの場合にのみ実行されます。
条件部分を丸かっこで囲む必要はありません。逆に波かっこ{ }は常に必要です。
else文
else文はプログラミングにおける条件を記述する文であり、ifがfalseと評価された場合にelseブロックのコードを実行します。
joey_age := 12
kevin_age := 15
if joey_age > kevin_age {
println("Joey is older")
} else {
println("Kevin is older")
}
上のコード例では、elseブロック内のコードが実行されます(ifはfalseと評価されるため)。
else if文
if...else文は、評価式がtrueかfalseかに応じて異なるコードを実行します。しかし可能性のある選択肢が3つ以上になることもあります。if...else if...elseのように重ねることで、複数の評価式をチェックして実行する文を切り替えることができます。
tom_age := 20
ashia_age := 38
if tom_age < ashia_age {
println("Tom is younger than Ashia")
} else if tom_age > ashia_age {
println("Tom is older than Ashia")
} else {
println("Tom and Ashia are the same age")
}
上の出力結果:
Tom is younger than Asia
if..else文のネスト
if...else文をネストすることで、別のif文やelse...if文の中でif文やelse文やelse...if文を使えます。ネストは1回に留めるのがよい習慣です。
tom_age := 20
ashia_age := 38
if tom_age < ashia_age {
if tom_age < 18 {
println("tom_age < 18 and younger than Ashia.")
} else {
println("tom_age >= 18 and younger than Ashia.")
}
} else if tom_age > ashia_age {
println("$tom_age > $ashia_age")
} else {
println("$tom_age == $ashia_age")
}
上の出力結果:
tom_age >= 18 and younger than Ashia.
if..elseを式として扱う
if..elseは式としても扱えます。
tom_age := 20
ashia_age := 38
s := if tom_age < ashia_age {
"Tom is the youngest"
} else {
"Ashia is the youngest"
}
print(s)
上の出力結果:
Tom is the youngest
演習
- integerを2つ受け取り、両者が等しいかどうかをチェックするVプログラムを書きましょう。
- 渡した数値が奇数か偶数かをチェックするVプログラムを書きましょう。
- 渡した数値が正か負かをチェックするVプログラムを書きましょう。
- 渡した年がうるう年かどうかをチェックするVプログラムを書きましょう。