✅ 조건문 (Conditional Statements)
- 주어진 조건식에 따라 코드 실행 흐름을 제어하는 구조
if, else if, else
int playerScore = 83;
if (playerScore >= 90)
Console.WriteLine("A Rank");
else if (playerScore >= 80)
Console.WriteLine("B Rank");
else
Console.WriteLine("C Rank 이하");
>>> B Rank
- if: 조건이 true면 실행
- else if: 위 조건이 false이고, 해당 조건이 true면 실행
- else: 위 모든 조건이 false일 때 실행
switch
enum ItemType {Weapon = 1, Armor, Potion, None};
ItemType itemType = ItemType.Armor;
switch(itemType)
{
case ItemType.Weapon:
Console.WriteLine("아이템 타입: 무기");
break;
case ItemType.Armor:
Console.WriteLine("아이템 타입: 방어구");
break;
case ItemType.Potion:
Console.WriteLine("아이템 타입: 포션");
break;
default:
Console.WriteLine("아이템 타입: None");
break;
}
>>> 아이템 타입: 방어구
🔁 반복문 (Loop Statements)
for (반복 횟수가 명확할 때 유용)
int monsterCount = 20;
for(int i = 0; i < monsterCount; i++)
{
Console.WriteLine($"몬스터 {i + 1}마리 소환 완료");
}
while (조건이 true일 동안 계속 반복, 조건에 따른 반복 여부 정하고 싶을때 사용)
int playerHp = 100;
while(playerHp > 0)
{
Console.WriteLine($"현재 체력: {playerHp}");
playerHp -= 10;
}
foreach (배열, 리스트 등 컬렉션 요소 반복에 적합)
string[] inventory = {"검", "방패", "철갑옷", "던전 열쇠"};
foreach (string item in inventory)
{
Console.WriteLine($"인벤토리 아이템: {item}");
}
- for: 일정 횟수만큼 반복해야 할 때
- while: 조건이 만족될 때 까지 계속해서 반복
- foreach: 전체 리스트 순회