C#/C#_기초강의
(C#) 제어문: 선택문(Selection statements) if, else, switch
코딩ABC
2023. 4. 21. 11:51
반응형
if 문
if문은 if 부울식의 값에 따라서 실행할 문을 선택합니다.
다음의 if ~ else 구문은 score 변수의 값에 따라서 둘 중 한 개의 문장을 실행합니다.
int score = 80;
if(score >=60)
{
Console.WriteLine("합격");
}
else
{
Console.WriteLine("불합격");
}
else가 없는 if 구문은 조건식이 참(true)일 떄만 실행이 됩니다.
int score = 90;
if(score >=80)
{
Console.WriteLine("참 잘했습니다");
}
if 구문을 중첩하여 여러 개의 조건을 확인할 수 있습니다.
static void Main(string[] args)
{
int score = int.Parse(Console.ReadLine());
if(score >=90)
{
Console.WriteLine("A학점");
}
else if (score >= 80)
{
Console.WriteLine("B학점");
}
else if (score >= 70)
{
Console.WriteLine("C학점");
}
else if (score >= 60)
{
Console.WriteLine("D학점");
}
else
{
Console.WriteLine("F학점");
}
}
switch 문
switch 문은 switch 다음의 식과 패턴이나 값이 일치하는 문을 선택해서 실행합니다.
static void Main(string[] args)
{
int score = int.Parse(Console.ReadLine());
switch(score/10)
{
case 10:
case 9:
Console.WriteLine("A학점");
break;
case 8:
Console.WriteLine("B학점");
break;
default:
Console.WriteLine("F학점");
break;
case 7:
Console.WriteLine("C학점");
break;
case 6:
Console.WriteLine("D학점");
break;
}
}
switch 문의 마지막 case에는 반드시 break 구문을 포함해야 하며, break 문을 사용하지 않으면 자동으로 wwitch 구문을 벗어나지 않습니다.
default 구문은 switch 문의 어디에나 올 수 있으며, 어느 위치에 있든지 맨 마지막에 평가됩니다.
static void Main(string[] args)
{
int score = int.Parse(Console.ReadLine());
switch(score/10)
{
case 3:
case 4:
case 5:
Console.WriteLine("봄");
break;
case 6:
case 7:
case 8:
Console.WriteLine("여름");
break;
case 9:
case 10:
case 11:
Console.WriteLine("가을");
break;
default:
Console.WriteLine("겨울");
break;
}
}
반응형