C# 조건문 완전 정복: if, if-else, if-else if, 중첩 if 문법과 예제
C# 조건문 완전 정복: if, if-else, if-else if, 중첩 if
이 글에서는 C#에서 if, if...else, if...else if 문을 사용하여 프로그램 실행 흐름을 제어하는 방법을 학습합니다.
조건 테스트는 모든 프로그래밍 언어의 핵심입니다. C#에서 조건문은 불리언 식을 평가하여 어느 코드 블록을 실행할지 결정합니다. 이 조건은 주로 사용자 입력, 시스템 상태, 시간 등 런타임 요소에 의해 결정됩니다.
C# if (If-Then) 문
C#에서 가장 단순한 조건 논리는 if 문으로, 불리언 식이 true로 평가될 때 코드 블록을 실행합니다. 문법은 직관적입니다:
if (booleanExpression) {
// booleanExpression이 true일 때 실행할 코드
}
booleanExpression은 true 또는 false를 반환해야 합니다.
true면 중괄호 안의 문장이 실행됩니다.
false면 해당 문장은 건너뜁니다.
예시:
if (number < 5) {
number += 5;
}
number가 5 미만일 때만 number += 5;가 실행됩니다.
if 문 동작 원리
예제 1: 기본 if 문
using System;
namespace Conditional {
class IfStatement {
public static void Main(string[] args) {
int number = 2;
if (number < 5) {
Console.WriteLine($"{number} is less than 5");
}
Console.WriteLine("This statement is always executed.");
}
}
}
출력:
2 is less than 5
This statement is always executed.
number를 10으로 변경하면:
This statement is always executed.
number < 5가 false이므로 if 블록이 건너뛰어집니다.
C# if...else (If-Then-Else) 문
불리언 테스트의 두 결과를 모두 처리하려면 else 블록을 추가합니다:
if (booleanExpression) {
// true일 때 실행
} else {
// false일 때 실행
}
예시:
if (number < 5) {
number += 5;
} else {
number -= 5;
}
number가 5 미만이면 첫 번째 분기, 아니면 두 번째 분기 실행.
if...else 문 동작 원리
예제 2: if...else 사용
using System;
namespace Conditional {
class IfElseStatement {
public static void Main(string[] args) {
int number = 12;
if (number < 5) {
Console.WriteLine($"{number} is less than 5");
} else {
Console.WriteLine($"{number} is greater than or equal to 5");
}
Console.WriteLine("This statement is always executed.");
}
}
}
number = 12일 때 출력:
12 is greater than or equal to 5
This statement is always executed.
number = 2일 때:
2 is less than 5
This statement is always executed.
간단한 if...else는 삼항 연산자로 대체 가능합니다.
C# if...else if (If-Then-Else If) 문
여러 조건을 순차 평가하려면 초기 if 뒤에 else if를 연쇄합니다:
if (condition1) {
// condition1 코드
} else if (condition2) {
// condition2 코드
} else if (condition3) {
// condition3 코드
} else {
// 모든 조건이 false일 때 코드
}
위에서 아래로 평가되며, 첫 true 조건에서 실행을 멈춥니다. 모두 맞지 않으면 else 블록 실행.
이산 값 처리에는 switch 문이 더 깔끔할 수 있습니다.
예제 3: if...else if 사용
using System;
namespace Conditional {
class IfElseIfStatement {
public static void Main(string[] args) {
int number = 12;
if (number < 5) {
Console.WriteLine($"{number} is less than 5");
} else if (number > 5) {
Console.WriteLine($"{number} is greater than 5");
} else {
Console.WriteLine($"{number} is equal to 5");
}
}
}
}
number = 12 출력:
12 is greater than 5
number를 4나 5로 바꾸면 출력이 달라집니다.
중첩 if...else 문
중첩 if...else는 조건 블록 안에 또 다른 조건 블록을 두어 다단계 의사결정 로직을 구현합니다. 일반적인 패턴:
using System;
namespace Conditional {
class Nested {
public static void Main(string[] args) {
int first = 7, second = -23, third = 13;
if (first > second) {
if (first > third) {
Console.WriteLine($"{first} is the largest");
} else {
Console.WriteLine($"{third} is the largest");
}
} else {
if (second > third) {
Console.WriteLine($"{second} is the largest");
} else {
Console.WriteLine($"{third} is the largest");
}
}
}
}
}