[C#] 조건문과 반복문

장민제·2025년 4월 14일

C# Study

목록 보기
3/11
post-thumbnail

✅ 조건문 (Conditional Statements)

  • 주어진 조건식에 따라 코드 실행 흐름을 제어하는 구조

if, else if, else

int  playerScore = 83;

if (playerScore >= 90)	// 점수가 90점 이상일 때
	Console.WriteLine("A Rank");
    
else if (playerScore >= 80)	// (점수가 90점 미만) 80점 이상일 때
	Console.WriteLine("B Rank");
    
else	// (80점 미만일 때) 그 외
	Console.WriteLine("C Rank 이하");
    
>>> B Rank
  • if: 조건이 true면 실행
  • else if: 위 조건이 false이고, 해당 조건이 true면 실행
  • else: 위 모든 조건이 false일 때 실행

switch

// 아이템 타입을 정의하는 열거형(enum)
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;

// i가 0부터 19까지 반복하며 몬스터 20마리 소환
for(int i = 0; i < monsterCount; i++)
{
	Console.WriteLine($"몬스터 {i + 1}마리 소환 완료");
}

while (조건이 true일 동안 계속 반복, 조건에 따른 반복 여부 정하고 싶을때 사용)

int playerHp = 100;

// 체력이 0보다 크면 반복해서 체력 10 감소
while(playerHp > 0)
{
	Console.WriteLine($"현재 체력: {playerHp}");
    playerHp -= 10;
}

foreach (배열, 리스트 등 컬렉션 요소 반복에 적합)

string[] inventory = {"검", "방패", "철갑옷", "던전 열쇠"};

// 인벤토리 안에 존재하는 모든 아이템 출력
foreach (string item in inventory)
{
	Console.WriteLine($"인벤토리 아이템: {item}");
}
  • for: 일정 횟수만큼 반복해야 할 때
  • while: 조건이 만족될 때 까지 계속해서 반복
  • foreach: 전체 리스트 순회
profile
Unity, C#

0개의 댓글