はじめに
この実験では、C プログラミングにおける意思決定構造を構築する方法を学びます。まず、if 文の基本概念を理解することから始めます。これにより、プログラムが特定の条件に基づいて意思決定を行うことができます。次に、不等号演算子、if-else 文のチェーン、論理演算子を使った式の組み合わせを調べ、条件付き論理を練習します。この実験が終わるとき、C プログラムにおいて意思決定構造を作成する方法を十分に理解し、より洗練された賢いコードを書けるようになります。
if 文を理解する
このステップでは、C プログラミングにおける if 文の基本概念を学びます。これは、コード内に意思決定構造を作成する際に不可欠です。if 文を使うことで、プログラムは特定の条件に基づいて意思決定を行い、異なるコードブロックを実行することができます。
まず、基本的な if 文の構文を示す簡単な C プログラムを作成しましょう。VSCode エディタを開き、~/project ディレクトリに if_statement.c という新しいファイルを作成します。
cd ~/project
touch if_statement.c
#include <stdio.h>
int main() {
int temperature = 25;
if (temperature > 30) {
printf("It's a hot day!\n");
}
if (temperature <= 30) {
printf("The temperature is comfortable.\n");
}
return 0;
}
このプログラムをコンパイルして実行します。
gcc if_statement.c -o if_statement
./if_statement
実行結果の例:
The temperature is comfortable.
if 文を分解してみましょう。
ifキーワードの後には、丸括弧()で囲まれた条件が続きます。- 条件は論理式で、真または偽に評価されます。
- 条件が真の場合、波括弧
{}内のコードブロックが実行されます。 - 条件が偽の場合、コードブロックはスキップされます。
次に、if 文がユーザー入力に基づいてどのように意思決定を行うかを示す、より対話型の例を作成しましょう。
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) {
printf("You are eligible to vote.\n");
}
if (age < 18) {
printf("You are not old enough to vote.\n");
}
return 0;
}
このプログラムをコンパイルして実行します。
gcc voting_eligibility.c -o voting_eligibility
./voting_eligibility
実行結果の例:
Enter your age: 20
You are eligible to vote.
覚えておくべき要点:
- if 文を使うことで、プログラムは意思決定を行うことができます。
- 条件は真または偽に評価されます。
- 真の条件に対応するコードブロックのみが実行されます。
>、<、>=、<=、==、!=のような比較演算子を使用できます。
不等号演算子を調べる
このステップでは、より複雑な条件文を作成するために不可欠な不等号演算子を調べることで、C プログラミングをさらに深く学びます。不等号演算子を使うことで、値を比較し、それらの関係に基づいて意思決定を行うことができます。
さまざまな不等号演算子を示すために、~/project ディレクトリに inequality_operators.c という新しいファイルを作成しましょう。
cd ~/project
touch inequality_operators.c
#include <stdio.h>
int main() {
int x = 10;
int y = 20;
// 等しい (==) 演算子
if (x == y) {
printf("x is equal to y\n");
} else {
printf("x is not equal to y\n");
}
// 等しくない (!=) 演算子
if (x!= y) {
printf("x is different from y\n");
}
// 大きい (>) 演算子
if (y > x) {
printf("y is greater than x\n");
}
// 小さい (<) 演算子
if (x < y) {
printf("x is less than y\n");
}
// 大きいか等しい (>=) 演算子
if (y >= x) {
printf("y is greater than or equal to x\n");
}
// 小さいか等しい (<=) 演算子
if (x <= y) {
printf("x is less than or equal to y\n");
}
return 0;
}
このプログラムをコンパイルして実行します。
gcc inequality_operators.c -o inequality_operators
./inequality_operators
実行結果の例:
x is not equal to y
x is different from y
y is greater than x
x is less than y
y is greater than or equal to x
x is less than or equal to y
ユーザー入力を使った不等号演算子の例をもう一つ作成しましょう。
#include <stdio.h>
int main() {
int score;
printf("Enter your exam score: ");
scanf("%d", &score);
if (score >= 90) {
printf("Excellent! You got an A.\n");
} else if (score >= 80) {
printf("Good job! You got a B.\n");
} else if (score >= 70) {
printf("Not bad. You got a C.\n");
} else if (score >= 60) {
printf("You passed. You got a D.\n");
} else {
printf("Sorry, you failed the exam.\n");
}
return 0;
}
このプログラムをコンパイルして実行します。
gcc grade_calculator.c -o grade_calculator
./grade_calculator
実行結果の例:
Enter your exam score: 85
Good job! You got a B.
覚えておくべき要点:
- 不等号演算子は値の比較に役立ちます。
==は値が等しいかどうかを確認します。!=は値が等しくないかどうかを確認します。>は左辺の値が右辺の値より大きいかどうかを確認します。<は左辺の値が右辺の値より小さいかどうかを確認します。>=は左辺の値が右辺の値以上であるかどうかを確認します。<=は左辺の値が右辺の値以下であるかどうかを確認します。
if-else 文をチェーン化する
このステップでは、C プログラミングにおいて if-else 文をチェーン化して、より複雑な意思決定構造を作成する方法を学びます。if-else 文をチェーン化することで、複数の条件を処理し、以前の条件が満たされない場合に代替のコードパスを提供することができます。
チェーン化された if-else 文を示すために、~/project ディレクトリに weather_advisor.c というファイルを作成しましょう。
cd ~/project
touch weather_advisor.c
#include <stdio.h>
int main() {
int temperature;
char weather_type;
printf("Enter the temperature: ");
scanf("%d", &temperature);
printf("Enter the weather type (S for sunny, R for rainy, C for cloudy): ");
scanf(" %c", &weather_type);
if (temperature > 30 && weather_type == 'S') {
printf("It's a hot and sunny day. Stay hydrated and use sunscreen!\n");
} else if (temperature > 30 && weather_type == 'R') {
printf("It's hot and rainy. Be careful of potential thunderstorms.\n");
} else if (temperature > 30 && weather_type == 'C') {
printf("It's hot and cloudy. Wear light clothing.\n");
} else if (temperature >= 20 && temperature <= 30) {
printf("The temperature is comfortable.\n");
} else if (temperature < 20) {
printf("It's a bit cool today. Consider wearing a light jacket.\n");
} else {
printf("Invalid input. Please check your temperature and weather type.\n");
}
return 0;
}
このプログラムをコンパイルして実行します。
gcc weather_advisor.c -o weather_advisor
./weather_advisor
実行結果の例:
Enter the temperature: 35
Enter the weather type (S for sunny, R for rainy, C for cloudy): S
It's a hot and sunny day. Stay hydrated and use sunscreen!
もう一つの例を作成して、チェーン化された if-else 文のより実用的な使い方を示しましょう。
#include <stdio.h>
int main() {
char category;
double price, discount = 0.0;
printf("Enter product category (A/B/C): ");
scanf(" %c", &category);
printf("Enter product price: ");
scanf("%lf", &price);
if (category == 'A') {
if (price > 1000) {
discount = 0.2; // 高額の A カテゴリに対する 20% 割引
} else {
discount = 0.1; // A カテゴリに対する 10% 割引
}
} else if (category == 'B') {
if (price > 500) {
discount = 0.15; // 高額の B カテゴリに対する 15% 割引
} else {
discount = 0.05; // B カテゴリに対する 5% 割引
}
} else if (category == 'C') {
if (price > 200) {
discount = 0.1; // 高額の C カテゴリに対する 10% 割引
} else {
discount = 0.0; // 低額の C カテゴリには割引なし
}
} else {
printf("Invalid category!\n");
return 1;
}
double discounted_price = price * (1 - discount);
printf("Original price: $%.2f\n", price);
printf("Discount: %.0f%%\n", discount * 100);
printf("Discounted price: $%.2f\n", discounted_price);
return 0;
}
このプログラムをコンパイルして実行します。
gcc discount_calculator.c -o discount_calculator
./discount_calculator
実行結果の例:
Enter product category (A/B/C): B
Enter product price: 600
Original price: $600.00
Discount: 15%
Discounted price: $510.00
覚えておくべき要点:
- チェーン化された if-else 文は複数の条件を処理できます。
- 各条件は上から下に順にチェックされます。
- 最初に一致する条件のコードブロックのみが実行されます。
elseブロックは以前の条件が満たされない場合のデフォルトのアクションを提供します。- より複雑な意思決定構造を作成するために、if-else 文をネストさせることができます。
論理演算子を使って式を結合する
このステップでは、C プログラミングにおいて論理演算子を使って複数の条件を組み合わせる方法を学びます。論理演算子を使うことで、複数の式を結合して、より複雑な条件文を作成することができます。
3 つの主な論理演算子:AND (&&)、OR (||)、NOT (!) を示すために、~/project ディレクトリに logical_operators.c というファイルを作成しましょう。
cd ~/project
touch logical_operators.c
#include <stdio.h>
int main() {
int age, income;
char is_student;
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your annual income: ");
scanf("%d", &income);
printf("Are you a student? (Y/N): ");
scanf(" %c", &is_student);
// AND (&&) 演算子:両方の条件が真でなければならない
if (age >= 18 && income < 30000) {
printf("You qualify for a basic credit card.\n");
}
// OR (||) 演算子:少なくとも 1 つの条件が真でなければならない
if (age < 25 || is_student == 'Y') {
printf("You may be eligible for a student discount.\n");
}
// 複数の条件を組み合わせる
if ((age >= 18 && income >= 30000) || (is_student == 'Y')) {
printf("You qualify for a premium credit card.\n");
}
// NOT (!) 演算子:条件を否定する
if (!(age < 18)) {
printf("You are an adult.\n");
}
return 0;
}
このプログラムをコンパイルして実行します。
gcc logical_operators.c -o logical_operators
./logical_operators
実行結果の例:
Enter your age: 22
Enter your annual income: 25000
Are you a student? (Y/N): Y
You qualify for a basic credit card.
You may be eligible for a student discount.
You qualify for a premium credit card.
You are an adult.
もう一つの例を作成して、より複雑な論理条件を示しましょう。
#include <stdio.h>
int main() {
char membership_type;
int visits_per_month, total_spending;
printf("Enter your membership type (B for Bronze, S for Silver, G for Gold): ");
scanf(" %c", &membership_type);
printf("Enter number of visits per month: ");
scanf("%d", &visits_per_month);
printf("Enter total monthly spending: ");
scanf("%d", &total_spending);
// 複数の論理演算子を使った複雑な条件
if ((membership_type == 'G') ||
(membership_type == 'S' && visits_per_month >= 10) ||
(membership_type == 'B' && total_spending > 500)) {
printf("You are eligible for a special promotion!\n");
}
// 複雑な条件で NOT 演算子を使う
if (!(membership_type == 'B' && visits_per_month < 5)) {
printf("You can access additional membership benefits.\n");
}
return 0;
}
このプログラムをコンパイルして実行します。
gcc membership_conditions.c -o membership_conditions
./membership_conditions
実行結果の例:
Enter your membership type (B for Bronze, S for Silver, G for Gold): S
Enter number of visits per month: 12
Enter total monthly spending: 300
You are eligible for a special promotion!
You can access additional membership benefits.
覚えておくべき要点:
&&(AND) 演算子:両方の条件が真でなければならない||(OR) 演算子:少なくとも 1 つの条件が真でなければならない!(NOT) 演算子:条件を否定する- 複雑な論理を作成するために、複数の条件を組み合わせることができる
- 評価の順序を明確にするために、丸括弧を使うことができる
条件付き論理を練習する
この最後のステップでは、C における意思決定構造に関する学んだことすべてを適用して、複数の条件付き論理手法を示す包括的なプログラムを作成します。
ユーザーが財務的な意思決定を行うのを支援する、~/project ディレクトリに personal_finance_advisor.c という多目的のプログラムを作成しましょう。
cd ~/project
touch personal_finance_advisor.c
#include <stdio.h>
int main() {
double income, expenses, savings;
char employment_status, age_group;
// 財務情報を入力する
printf("Enter your monthly income: $");
scanf("%lf", &income);
printf("Enter your monthly expenses: $");
scanf("%lf", &expenses);
printf("Enter your current savings: $");
scanf("%lf", &savings);
printf("Employment status (F for Full-time, P for Part-time, U for Unemployed): ");
scanf(" %c", &employment_status);
printf("Age group (Y for Young (18-35), M for Middle-aged (36-55), S for Senior (56+)): ");
scanf(" %c", &age_group);
// 貯金率を計算する
double savings_rate = (savings / income) * 100;
double disposable_income = income - expenses;
// 複雑な条件付き論理を使った財務アドバイス
printf("\n--- Financial Analysis ---\n");
// 貯金アドバイス
if (savings_rate < 10) {
printf("Warning: Your savings rate is low (%.2f%%).\n", savings_rate);
} else if (savings_rate >= 10 && savings_rate < 20) {
printf("Good start! Your savings rate is moderate (%.2f%%).\n", savings_rate);
} else {
printf("Excellent! Your savings rate is strong (%.2f%%).\n", savings_rate);
}
// 投資推奨
if ((employment_status == 'F' && disposable_income > 500) ||
(age_group == 'Y' && savings > 5000)) {
printf("Recommendation: Consider starting an investment portfolio.\n");
}
// 緊急資金アドバイス
if (savings < (expenses * 3)) {
printf("Advice: Build an emergency fund covering at least 3 months of expenses.\n");
}
// 支出管理
if (expenses > (income * 0.7)) {
printf("Alert: Your expenses are too high compared to your income.\n");
}
// 特別条件
if ((age_group == 'Y' && employment_status == 'F') ||
(savings > (income * 2))) {
printf("You are in a good financial position!\n");
}
// 詳細な財務健康診断
if (!(disposable_income < 0)) {
printf("Your disposable income is: $%.2f\n", disposable_income);
} else {
printf("Warning: Your expenses exceed your income.\n");
}
return 0;
}
このプログラムをコンパイルして実行します。
gcc personal_finance_advisor.c -o personal_finance_advisor
./personal_finance_advisor
実行結果の例:
Enter your monthly income: $5000
Enter your monthly expenses: $3500
Enter your current savings: $10000
Employment status (F for Full-time, P for Part-time, U for Unemployed): F
Age group (Y for Young (18-35), M for Middle-aged (36-55), S for Senior (56+)): Y
--- Financial Analysis ---
Good start! Your savings rate is moderate (40.00%).
Recommendation: Consider starting an investment portfolio.
You are in a good financial position!
Your disposable income is: $1500.00
条件付き論理をさらに練習するためのボーナスチャレンジプログラムを作成しましょう。
#include <stdio.h>
int main() {
int math_score, science_score, english_score;
char extra_credit;
printf("Enter Math score (0-100): ");
scanf("%d", &math_score);
printf("Enter Science score (0-100): ");
scanf("%d", &science_score);
printf("Enter English score (0-100): ");
scanf("%d", &english_score);
printf("Did you complete extra credit? (Y/N): ");
scanf(" %c", &extra_credit);
// 平均点を計算する
double average = (math_score + science_score + english_score) / 3.0;
// 包括的な成績判定
if (average >= 90 ||
(extra_credit == 'Y' && average >= 85)) {
printf("Congratulations! You earned an A grade.\n");
} else if (average >= 80 ||
(extra_credit == 'Y' && average >= 75)) {
printf("Great job! You earned a B grade.\n");
} else if (average >= 70 ||
(extra_credit == 'Y' && average >= 65)) {
printf("You passed. You earned a C grade.\n");
} else {
printf("You need to improve. Consider retaking the courses.\n");
}
return 0;
}
このプログラムをコンパイルして実行します。
gcc grade_calculator.c -o grade_calculator
./grade_calculator
実行結果の例:
Enter Math score (0-100): 85
Enter Science score (0-100): 88
Enter English score (0-100): 92
Did you complete extra credit? (Y/N): N
Great job! You earned a B grade.
覚えておくべき要点:
- 論理演算子を使って複数の条件を組み合わせる
- 複雑な意思決定にはネストされた if-else 文を使う
- 端数ケースを考慮し、包括的な論理を提供する
- 複雑な問題を小さくて管理可能な条件に分解する
まとめ
この実験では、C プログラミングにおける if 文の基本概念を学びました。これは、コード内で意思決定構造を作成する際に不可欠です。if 文がどのようにプログラムに意思決定を行わせ、特定の条件に基づいて異なるコードブロックを実行するかを調べました。また、不等号演算子、if-else 文のチェーン化、論理演算子を使った式の組み合わせ、および条件付き論理の練習により、C プログラムでより複雑な意思決定構造を構築する方法を学びました。
この実験で扱った要点は、if 文の基本構文の理解、論理式を真偽値として評価すること、および条件に基づいて適切なコードブロックを実行することです。また、ユーザー入力に基づいて意思決定を行うために if 文をどのように使うかを学びました。これは、対話型アプリケーションを構築するための不可欠なスキルです。



