C# If-Else 문 이해하기: 초보자 가이드
C# 프로그래밍에서 조건에 기반한 의사 결정은 동적이고 반응성이 뛰어난 애플리케이션을 만드는 데 있어 기본적인 요소입니다. 바로 이런 부분에서 if-else 문이 중요한 역할을 합니다. C#의 if-else 문은 지정된 조건이 참인지 거짓인지에 따라 프로그램이 서로 다른 코드 블록을 실행하도록 합니다.
이 가이드는 LaylaCodesIt 의 ' C# for Beginners Part 2 - 'if-else' 문과 'while' 루프 작성법 배우기' 영상에서 영감을 받아 작성되었으며, C#에서 if-else 문의 기본 사항, 부울 조건을 작성할 때 조건 연산자와 논리 연산자의 사용법, 그리고 프로그램이 사용자 입력과 지능적으로 상호 작용하도록 만드는 방법을 소개합니다.
조건 논리 소개
조건 논리는 프로그램이 특정 조건에 따라 결정을 내릴 수 있도록 합니다. 레이라의 영상은 조건 논리의 한 예인 if-else 문의 개념과 구문을 소개합니다. if-else 문은 특정 조건이 참인지 거짓인지에 따라 다른 코드 블록을 실행합니다.
다음 코드 예제에서 Layla는 사용자가 치즈를 좋아하는지 묻는 인사 메시지를 작성합니다.
// Asking the user a question and storing their response
Console.WriteLine($"Hello {name}, do you like cheese?");
string doTheyLikeCheese = Console.ReadLine();// Asking the user a question and storing their response
Console.WriteLine($"Hello {name}, do you like cheese?");
string doTheyLikeCheese = Console.ReadLine();Simple If-Else Statement in C
그러면 이 if-else 조건문은 사용자의 답변을 확인하고 사용자가 말한 내용에 따라 출력 응답을 변경합니다. 조건 연산자를 사용하여 조건을 구성하고, 그 결과에 따라 if-else 블록 안의 문장이 실행됩니다. 다음은 한 줄짜리 간단한 예시입니다.
// Checking the user's response and providing appropriate output
if (doTheyLikeCheese == "yes")
{
Console.WriteLine("Here is a lump of cheese.");
}
else
{
Console.WriteLine("Here is a lump of coal.");
}// Checking the user's response and providing appropriate output
if (doTheyLikeCheese == "yes")
{
Console.WriteLine("Here is a lump of cheese.");
}
else
{
Console.WriteLine("Here is a lump of coal.");
}사용자가 '예'라고 답하면, if 문 안의 코드는 치즈 한 덩어리를 제공한다는 메시지를 표시합니다. 사용자가 '예' 이외의 다른 답변을 하면 else 블록에서 "여기 석탄 덩어리가 있습니다."라는 메시지가 출력됩니다.
대소문자 구분 문제
기본적인 if-else 문에서 흔히 발생하는 문제는 대소문자 구분입니다. 사용자가 'yes' 대신 'Yes'를 입력하면 프로그램은 이를 유효한 입력으로 인식하지 않습니다. 이를 해결하기 위해 Layla는 사용자 입력을 자동으로 소문자로 변환하고 대소문자 구분 문제를 피하는 ToLower() 메서드를 사용합니다.
// Using ToLower() to handle case sensitivity in user input
if (doTheyLikeCheese.ToLower() == "yes")
{
Console.WriteLine("Here is a lump of cheese.");
}
else
{
Console.WriteLine("Here is a lump of coal.");
}// Using ToLower() to handle case sensitivity in user input
if (doTheyLikeCheese.ToLower() == "yes")
{
Console.WriteLine("Here is a lump of cheese.");
}
else
{
Console.WriteLine("Here is a lump of coal.");
}여러 조건 처리
이어서 레일라는 else-if 문을 사용하여 두 개 이상의 가능한 응답을 처리하는 방법을 설명합니다. 여기서 프로그램은 사용자가 '예', '아니오' 또는 다른 어떤 응답을 하든 여러 조건문을 확인합니다.
// Checking multiple conditions using else-if
if (doTheyLikeCheese.ToLower() == "yes")
{
Console.WriteLine("Here is a lump of cheese.");
}
else if (doTheyLikeCheese.ToLower() == "no")
{
Console.WriteLine("Here is a lump of coal.");
}
else
{
Console.WriteLine("Please give a yes or no answer.");
}// Checking multiple conditions using else-if
if (doTheyLikeCheese.ToLower() == "yes")
{
Console.WriteLine("Here is a lump of cheese.");
}
else if (doTheyLikeCheese.ToLower() == "no")
{
Console.WriteLine("Here is a lump of coal.");
}
else
{
Console.WriteLine("Please give a yes or no answer.");
}이전과 마찬가지로, if 문의 부울 표현식이 참이면 사용자가 '예'라고 답할 때 프로그램이 치즈 한 덩어리를 제공합니다. 하지만 else-if 문에서는 다른 응답에 대해서는 석탄 덩어리를 제공하던 것을, 이제는 사용자가 '아니오'라고 응답했을 때만 석탄 덩어리를 제공하도록 변경되었습니다. 사용자가 '예' 또는 '아니오' 이외의 다른 답변을 하면 프로그램의 else 부분에서 사용자에게 '예' 또는 '아니오'로 다시 답변하도록 요청합니다. 위 코드의 실행 결과를 살펴보겠습니다. (이미지는 개선될 수 있습니다.)

반복문을 사용하기
사용자가 유효한 응답을 제공하도록 하기 위해 반복문이 도입되었습니다. 반복문은 사용자가 정답을 입력할 때까지 반복적으로 입력을 요청할 수 있습니다. 이것을 'while' 루프라고 하며, 다음 예는 작동 방식을 보여줍니다.
// Using a while loop to repeatedly ask for valid input
bool hasAnswered = false;
while (!hasAnswered)
{
// Checking the user's response and setting hasAnswered to true for valid responses
if (doTheyLikeCheese.ToLower() == "yes")
{
Console.WriteLine("Here is a lump of cheese.");
hasAnswered = true;
}
else if (doTheyLikeCheese.ToLower() == "no")
{
Console.WriteLine("Here is a lump of coal.");
hasAnswered = true;
}
else
{
Console.WriteLine("Please give a yes or no answer.");
doTheyLikeCheese = Console.ReadLine();
}
}// Using a while loop to repeatedly ask for valid input
bool hasAnswered = false;
while (!hasAnswered)
{
// Checking the user's response and setting hasAnswered to true for valid responses
if (doTheyLikeCheese.ToLower() == "yes")
{
Console.WriteLine("Here is a lump of cheese.");
hasAnswered = true;
}
else if (doTheyLikeCheese.ToLower() == "no")
{
Console.WriteLine("Here is a lump of coal.");
hasAnswered = true;
}
else
{
Console.WriteLine("Please give a yes or no answer.");
doTheyLikeCheese = Console.ReadLine();
}
}위 예시에서 루프는 사용자가 '예' 또는 '아니오'로 응답할 때까지 계속해서 사용자에게 메시지를 표시합니다. 레이라의 영상에서 코드가 실행될 때 어떤 모습인지 직접 확인할 수 있습니다.

if-else 문 - 요약
요약하자면:
- if-else 문은 코드에서 결정을 내릴 수 있습니다.
- else-if 문을 사용하면 여러 조건을 처리할 수 있습니다.
- 반복문은 사용자가 올바르게 응답하도록 보장합니다.
조건 논리는 C# 프로그래밍 언어의 기본 요소이므로 이러한 개념을 연습하고 코드에 포함시키는 것이 좋습니다. 그리고 이것은 단지 시작일 뿐입니다. if 문, else 문, else-if 문, if-else 문 안에 또 다른 if-else 문(중첩 if-else 문이라고도 함), switch 문 등 조건 논리는 프로그램의 작동 방식을 극적으로 바꿀 수 있으며, 배울 것이 무궁무진합니다.
결론
짜잔! 이것으로 if-else 문과 while 반복문에 대한 초보자 가이드가 끝났습니다. 앞서 언급했듯이 이 가이드는 LaylaCodesIt의 채널에서 영감을 받았습니다. 그녀의 채널에서 위의 모든 내용에 대한 비디오 데모와 C# 프로그래밍에 대한 더 자세한 정보를 확인해 보세요.
그동안 그녀가 좋아하는 크리에이터, 튜토리얼, 학습 자료 등을 공유하는 다른 리소스도 확인해 보세요. C# 실력 향상에 도움이 될 거예요. 즐거운 코딩 되세요!




