목차
C# 조건문
if 구문
if...else... 구문
if...else if...else 구문
3항 조건문
C# 조건문
1.
C#은 수학의 비교 및 논리 연산자 이용해 조건 판별 가능.
(예) < , <= , > , >= , == , !=
2.
if 구문 : if 조건이 참이면 실행.
else 구문 : 앞서 지정한 if (또는, else if) 조건이 거짓일 때 실행.
else if 구문 : 앞서 지정한 조건이 거짓일 때 새로 시험할 조건문.
cf.
switch 구문 : 각각의 경우에 실행할 조건문 지정.
if 구문
※ if는 소문자로 기재.
※ 대문자 사용해 If (또는, IF)로 적으면 에러 발생.
if (조건식) {
조건이 참일 때 실행할 코드
}
[예제1] 숫자 비교해 참인지 판별
using System;
namespace Homzzang
{
class Program
{
static void Main(string[] args)
{
if (4 > 3)
{
Console.WriteLine("참");
}
}
}
}
[예제2] 변수 비교해 참인지 판별
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 4;
int y = 3;
if (x > y)
{
Console.WriteLine("참");
}
}
}
}
if...else... 구문
if (조건식) {
조건이 참일 때 실행할 코드
} else {
조건이 거짓일 때 실행할 코드
}
[예제] - 오전/오후
using System;
namespace Homzzang
{
class Program
{
static void Main(string[] args)
{
int time = 15;
if (time < 12)
{
Console.WriteLine("오전");
}
else
{
Console.WriteLine("오후");
}
}
}
}
결과값: 오후
if...else if...else 구문
if(조건1) {
조건1이 참일 때 실행할 내용.
} else if(조건2) {
조건1이 거짓이면서, 조건2가 참일 때 실행할 내용.
} else {
조건1과 조건2 모두 거짓일 때 실행할 내용.
}
※ else if 구문은 여러 개 올 수 있음.
[예제] - 오전/오후/저녁
using System;
namespace Homzzang
{
class Program
{
static void Main(string[] args)
{
int time = 20;
if (time < 12)
{
Console.WriteLine("오전");
}
else if (time < 18)
{
Console.WriteLine("오후");
}
else
{
Console.WriteLine("저녁");
}
}
}
}
결과값: 저녁
3항 조건문
※ if...else... 조건문의 축약 표현.
※ 실무에서 아주 빈번하게 사용.
variable = (condition ) ? true_expression : false_expression ;
즉,
변수 = (조건식) ? 조건 참일 시 표현식 : 조건 거짓 시 표현식;
[예제] - 오전/오후
using System;
namespace Homzzang
{
class Program
{
static void Main(string[] args)
{
int time = 15;
string result = (time < 12) ? "오전" : "오후";
Console.WriteLine(result);
}
}
}
결과값: 오후
주소 복사
랜덤 이동
최신댓글