소개
이 랩에서는 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키워드 뒤에는 괄호()안에 조건이 옵니다.- 조건은 true 또는 false 로 평가되는 논리 표현식입니다.
- 조건이 true 이면 중괄호
{}안의 코드 블록이 실행됩니다. - 조건이 false 이면 코드 블록이 건너뜁니다.
이제 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 문을 사용하면 프로그램이 결정을 내릴 수 있습니다.
- 조건은 true 또는 false 로 평가됩니다.
- true 조건에 대한 코드 블록만 실행됩니다.
>,<,>=,<=,==,!=와 같은 비교 연산자를 사용할 수 있습니다.
부등호 연산자 탐구
이 단계에서는 더 복잡한 조건문을 만드는 데 필수적인 부등호 연산자를 탐구하여 C 프로그래밍을 더 깊이 파고들 것입니다. 부등호 연산자를 사용하면 값을 비교하고 관계를 기반으로 결정을 내릴 수 있습니다.
~/project 디렉토리에 inequality_operators.c라는 새 파일을 만들어 다양한 부등호 연산자를 시연해 보겠습니다.
cd ~/project
touch inequality_operators.c
#include <stdio.h>
int main() {
int x = 10;
int y = 20;
// Equal to (==) operator
if (x == y) {
printf("x is equal to y\n");
} else {
printf("x is not equal to y\n");
}
// Not equal to (!=) operator
if (x != y) {
printf("x is different from y\n");
}
// Greater than (>) operator
if (y > x) {
printf("y is greater than x\n");
}
// Less than (<) operator
if (x < y) {
printf("x is less than y\n");
}
// Greater than or equal to (>=) operator
if (y >= x) {
printf("y is greater than or equal to x\n");
}
// Less than or equal to (<=) operator
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 문을 연결하면 여러 조건을 처리하고 이전 조건이 충족되지 않을 때 대체 코드 경로를 제공할 수 있습니다.
~/project 디렉토리에 weather_advisor.c라는 파일을 만들어 연결된 if-else 문을 시연해 보겠습니다.
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; // 20% discount for high-value A category
} else {
discount = 0.1; // 10% discount for A category
}
} else if (category == 'B') {
if (price > 500) {
discount = 0.15; // 15% discount for high-value B category
} else {
discount = 0.05; // 5% discount for B category
}
} else if (category == 'C') {
if (price > 200) {
discount = 0.1; // 10% discount for high-value C category
} else {
discount = 0.0; // No discount for low-value C category
}
} 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 프로그래밍에서 논리 연산자를 사용하여 여러 조건을 결합하는 방법을 배우게 됩니다. 논리 연산자를 사용하면 여러 표현식을 연결하여 더 복잡한 조건문을 만들 수 있습니다.
~/project 디렉토리에 logical_operators.c라는 파일을 만들어 세 가지 주요 논리 연산자: AND (&&), OR (||), NOT (!):를 시연해 보겠습니다.
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 (&&) operator: Both conditions must be true
if (age >= 18 && income < 30000) {
printf("You qualify for a basic credit card.\n");
}
// OR (||) operator: At least one condition must be true
if (age < 25 || is_student == 'Y') {
printf("You may be eligible for a student discount.\n");
}
// Combining multiple conditions
if ((age >= 18 && income >= 30000) || (is_student == 'Y')) {
printf("You qualify for a premium credit card.\n");
}
// NOT (!) operator: Negates the condition
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);
// Complex condition using multiple logical operators
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");
}
// Demonstrating NOT operator with complex conditions
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) 연산자: 적어도 하나의 조건이 참이어야 합니다.!(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;
// Input financial information
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);
// Calculate savings rate
double savings_rate = (savings / income) * 100;
double disposable_income = income - expenses;
// Financial advice using complex conditional logic
printf("\n--- Financial Analysis ---\n");
// Savings advice
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);
}
// Investment recommendations
if ((employment_status == 'F' && disposable_income > 500) ||
(age_group == 'Y' && savings > 5000)) {
printf("Recommendation: Consider starting an investment portfolio.\n");
}
// Emergency fund advice
if (savings < (expenses * 3)) {
printf("Advice: Build an emergency fund covering at least 3 months of expenses.\n");
}
// Spending control
if (expenses > (income * 0.7)) {
printf("Alert: Your expenses are too high compared to your income.\n");
}
// Special conditions
if ((age_group == 'Y' && employment_status == 'F') ||
(savings > (income * 2))) {
printf("You are in a good financial position!\n");
}
// Detailed financial health assessment
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);
// Calculate average
double average = (math_score + science_score + english_score) / 3.0;
// Comprehensive grade determination
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 문을 사용하는 방법을 배웠으며, 이는 대화형 애플리케이션을 구축하는 데 필수적인 기술입니다.



