CSharp IF 조건문

양승준·2025년 3월 28일

CSharp

목록 보기
7/20
post-thumbnail

IF문 (if, else if, else)


IF

🧪 예제 코드

class Program
{
    static void Main(string[] args)
    {
        if(조건식)
        {
            // 실행 부분
        }
    }
}

🧪 예제 코드

class Program
{
    static void Main(string[] args)
    {
        int playerHp = 100;
        string inputDamage;
        int damageTaken = 0;

        // 입력
        Console.Write($"플레이어의 현재 체력은 {playerHp} 입니다.");
        Console.WriteLine("플레이어가 받을 피해를 입력해주세요.");
        Console.Write("[받을 데미지 입력]: ");
        inputDamage = Console.ReadLine();

        // 맞는지 판단
        if (int.TryParse(inputDamage, out damageTaken))
        {
            Console.WriteLine($"정상적인 데미지 값이 들어왔습니다. > 받는 데미지 값 {damageTaken}");
            Console.WriteLine($"-{damageTaken}!!!!!!!!");
        }

        // 피해 입는 식
        playerHp -= damageTaken; // playerHp = playerHp - damageTaken;
        Console.Write($"플레이어의 현재 체력은 {playerHp} 입니다.");
    }
}

정상적인 입력 시, 출력

플레이어의 현재 체력은 100 입니다.
플레이어가 받을 피해를 입력해주세요.
[받을 데미지 입력]: 10
정상적인 데미지 값이 들어왔습니다. > 받는 데미지 값 10
-10!!!!!!!!
플레이어의 현재 체력은 90 입니다.

비정상적인 입력 시, 출력

플레이어의 현재 체력은 100 입니다.
플레이어가 받을 피해를 입력해주세요.
[받을 데미지 입력]: aa
플레이어의 현재 체력은 100 입니다.

  • if문은 위의 코드와 같이 지정해준 조건에 맞다면 중괄호 안에 코드가 실행됩니다.
  • 그렇다면 만약 틀렸을 때는 어떻게 처리할까요? 그건 else문입니다.



IF ~ ELSE


🧪 예제 코드

class Program
{
    static void Main(string[] args)
    {
        if(조건식)
        {
            // 위 조건식이 맞았을 경우, 실행 부분
        }
        else
        {
            // 위 조건식이 틀렸을 경우, 실행 부분
        }
    }
}

🧪 응용 코드

class Program
{
    static void Main(string[] args)
    {
        int playerHp = 100;
        string inputDamage;
        int damageTaken = 0;

        // 입력
        Console.Write($"플레이어의 현재 체력은 {playerHp} 입니다.");
        Console.WriteLine("플레이어가 받을 피해를 입력해주세요.");
        Console.Write("[받을 데미지 입력]: ");
        inputDamage = Console.ReadLine();

        // 맞는지 판단
        if (int.TryParse(inputDamage, out damageTaken))
        {
            Console.WriteLine($"정상적인 데미지 값이 들어왔습니다. > 받는 데미지 값 {damageTaken}");
            Console.WriteLine($"-{damageTaken}!!!!!!!!");
        }
        else
        {
            damageTaken = 0;
            Console.WriteLine("비정상적인 데미지 값이 들어왔습니다. > 받는 데미지가 0으로 변경됩니다.");
        }

        // 피해 입는 식
        playerHp -= damageTaken; // playerHp = playerHp - damageTaken;
        Console.Write($"플레이어의 현재 체력은 {playerHp} 입니다.");
    }
}

정상적인 입력 시, 출력

플레이어의 현재 체력은 100 입니다.
플레이어가 받을 피해를 입력해주세요.
[받을 데미지 입력]: 10
정상적인 데미지 값이 들어왔습니다. > 받는 데미지 값 10
-10!!!!!!!!
플레이어의 현재 체력은 90 입니다.

비정상적인 입력 시, 출력

플레이어의 현재 체력은 100 입니다.
플레이어가 받을 피해를 입력해주세요.
[받을 데미지 입력]: aa
비정상적인 데미지 값이 들어왔습니다. > 받는 데미지가 0으로 변경됩니다.
플레이어의 현재 체력은 100 입니다.

  • 위의 코드들 보면, 맞으면 실행되는 코드와 틀렸을 때의 분기가 생겨서, 응용 코드 부분에서 잘못된 값이 들어왔을 때의 처리가 가능 해졌습니다.
    • 물론 처리 과정에서 각각의 이 if 문으로 처리도 가능합니다. 하지만 왜 이렇게 처리할까?라는 의문이 들었다면 삐빅! 천재이십니다. 2개의 분기중에 하나만 실행 시키고 싶을 때 꼭 필요하기 때문입니다. 그리고 if문이 2번 사용되면 그만큼 비교도 2번이 필요합니다.



IF ~ ELSE IF ~ ELSE


🧪 예제 코드

class Program
{
    static void Main(string[] args)
    {
        if(조건식)
        {
            // if 조건식이 맞았을 경우, 실행 부분
        }
        else if(조건식)
        {
            // 위 else if 조건식이 맞았을 경우, 실행 부분
        }
        else if(조건식)
        {
            // 위 else if 조건식이 맞았을 경우, 실행 부분
        }
        else if(조건식)
        {
            // 위 else if 조건식이 맞았을 경우, 실행 부분
        }
        else
        {
            // 위 조건식이 틀렸을 경우, 실행 부분
        }
    }
}

🧪 응용 코드

class Program
{
    static void Main(string[] args)
    {
        int score = 0;
        string inputScore;

        Console.WriteLine("당신의 랭크 점수를 입력해주세요.");
        Console.Write("[점수 입력]: ");
        inputScore = Console.ReadLine();

        if (int.TryParse(inputScore, out score))
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write("정상적인");
        }
        else
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.Write("비정상적인");
        }
        Console.WriteLine(" 점수 입력입니다.");
        Console.ResetColor();

        if (score <= 0)
        {
            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.WriteLine("[미배치]");
        }
        else if (score <= 50)
        {
            Console.ForegroundColor = ConsoleColor.DarkYellow;
            Console.WriteLine("[브론즈 랭크]");
        }
        else if (score <= 60)
        {
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine("[실버 랭크]");
        }
        else if (score <= 70)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("[골드 랭크]");
        }
        else if (score <= 80)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[플레티넘 랭크]");
        }
        else if (score <= 90)
        {
            Console.ForegroundColor = ConsoleColor.DarkBlue;
            Console.WriteLine("[다이야몬드 랭크]");
        }
        else if (score <= 100)
        {
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("[첼린저 랭크]");
        }
        else
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("[ERROR]");
        }
    }
}
  • 위의 코드는 각 점수에 맞는 티어를 배정해주는 프로그램입니다.
  • 위의 코드처럼 각 점수에 맞게 티어를 배정하는 등의 여러 개의 조건을 부여할 수 있습니다. 그리고 이 중 하나가 참이라면 그 조건문 안의 실행문만 실행됩니다.
  • 지금은 조건이 잘 적혀 있어서 문제가 없지만 (점수 >= 점수컷트라인)이라는 조건이 앞쪽에 있었다면, 점수가 아무리 높더라도 [미배치]라는 결과만 나왔을 것입니다. 그렇기에 조건에 따른 조건 순서 선정도 중요합니다.
profile
지모창말, 미모창.

0개의 댓글