Machineboy空
C# if문, switch문, for문, forEach문, while문 본문
완전 기초를 다시 다지고 가자.
조건문 구성할 때 switch문이 적절한 케이스였음에도 바로 생각나지 않아서 정리한다.
If문
특정 조건에 따라 코드를 실행할지 말지 결정할 수 있는 문법
if( 조건부 ) { 동작부 }
if( 기온이 0도 이하라면 ) { 물이 업니다. }
else { 물이 얼지 않습니다. }
else if문
두 가지 이상의 옵션이 필요할 때
if ( 기온이 0도 이하라면 ) { 물이 업니다. }
else if ( 기온이 100도 미만이라면 ) { 물이 얼지도 끓지도 않습니다. }
else { 물이 끓습니다. }
switch 문
어떤 값을 입력했는지에 따라 다르게 동작하는 문법
case가 동등하게 선택지로 주어지는 느낌
switch ( 비교할 값 ){
case 조건값1:
동작부분;
break;
case 조건값2:
동작부분;
break;
default:
동작부분;
}
//등급별 티켓 가격
switch (grade) {
case 'VIP':
Console.WriteLine($"{grade}석은 {VIPPrice}만원 입니다.");
break;
case 'R':
Console.WriteLine($"{grade}석은 {RPrice}만원 입니다.");
break;
case 'S':
Console.WriteLine($"{grade}석은 {SPrice}만원 입니다.");
break;
case 'A':
Console.WriteLine($"{grade}석은 {APrice}만원 입니다.");
break;
default:
Console.WriteLine("좌석을 선택해주세요.")
}
a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program
변수 또는 표현식의 값에 따라 프로그램의 흐름을 변경할 수 있도록 하는 선택 제어 메커니즘의 한 유형.
1) simplest ver. (string)
string direction = GetDirection();
switch(direction)
{
case "left":
GoLeft();
break;
case "right":
GoRight();
break;
default:
MarkTime();
break;
}
2) sophisticated ver. (down casting)
Animal animal = GetAnimal();
switch (animal)
{
case Dog canine:
case Coyote canine: // Animal 타입이 Dog거나 Coyote인 경우, canine이란 변수로 다운캐스팅하여 동작 수행
canine.Bark();
break;
case Cat cat when cat.HasOnly8Lives(): // Animal 타입이 Cat인 경우, cat이란 변수로 다운캐스팅
cat.IsCareful(); // 고양이가 9개의 목숨을 가지고 있다는 속담을 활용
cat.Meow();
break;
case Cat cat:
cat.Meow();
break;
}
예제) Football Match Reports
https://exercism.org/tracks/csharp/exercises/football-match-reports
Football Match Reports in C# on Exercism
Can you solve Football Match Reports in C#? Improve your C# skills with support from our world-class team of mentors.
exercism.org
public static string AnalyzeOffField(object report)
{
switch (report)
{
// object → int 로 다운캐스팅
case int num:
return $"There are {num} supporters at the match.";
// object → string 로 다운캐스팅
case string announce:
return announce;
// object → Incident 로 다운캐스팅
case Incident incident:
// object → Incident → Foul이라면
if (incident.GetType() == typeof(Foul))
return incident.GetDescription();
// object → Incident → Injury라면
else if (incident.GetType() == typeof(Injury))
return $"Oh no! {incident.GetDescription()} Medics are on the field.";
else
return incident.GetDescription();
// object → Manager으로 다운캐스팅
case Manager manager:
if (manager.Club != null)
return $"{manager.Name} ({manager.Club})";
else
return manager.Name;
default:
return "";
}
}
if문 vs switch 문
if문 | switch문 |
어떤 넓은 범위를 만족하는 조건식을 만들 때 | 특정한 값에 일치하는 조건을 만들 때 |
for 문
- 초기화 부분(initializer)
- executed onece before entering the loop. Usually used to define variables used within the loop
- 조건 부분(condition)
- executed before each loop iteration. The loop continues to execute while this evaluates to true.
- 추가동작 부분(iterator)
- execute after each loop iteration. Usually used to modify(often: increment/decrement) the loop variables
- 동작 부분(body)
- the code that gets executed each loop iteration
for (초기화부분; 조건부분; 추가동작부분){ 동작부분 }
// 초기화부분: 가장 먼저 딱 한 번 실행되는 것, for문 안에서 생성한 로컬 변수 사용, 생략 가능
// 조건부분: boolean으로 판단하여 true면 동작부분 실행
// 추가동작부분: 조건부분이 true이면, 동작부분 실행하고 그 다음 추가적으로 동작할 부분 작성, 생략 가능
// 1부터 100까지의 짝수를 출력하라
for(int i = 2; i <= 100 ; i+=2)
{
Console.WriteLine(i);
}
forEach 문
char[] vowels = new[] {'a', 'e', 'i', 'o', 'u'};
foreach(char vowel in vowels)
{
System.Console.Write(vowel); //aeiou
}
while 문
while( 조건부분 ){ 동작부분 }
// 100이하의 홀수를 출력하라.
int i = 1;
while(i <= 100){
if(i % 2 == 1){
Console.WriteLine(i);
}
i++;
}
for 문 vs while문
for문 | while문 |
조건 비교에 사용되는 값을 반복문 내부에서만 사용하고 반복이 끝나면 외부에서 사용할 수 없다. | 글로벌 변수를 조건 비교에 사용하고, 반복문 내부에서도 다루면서 종료된 다음 이 변수를 사용해야 할 때 for문 보다 while문 |
'언어 > C#' 카테고리의 다른 글
C# DateTime 시간, 날짜 다루기 - DateTime.Parse(), TimeSpan.FromSecond(), DateTime.Add(), DayOfWeek (0) | 2025.01.17 |
---|---|
C# Class 기초,필드, 메소드, 멤버, 접근자, 생성자, 예제 등 (0) | 2025.01.16 |
C# 컬렉션 - 배열, 다차원 배열 - rank, getLength, Array.IndexOf(), Array.Sort() (0) | 2025.01.15 |
C# 난수 생성 , Random.Next(), Random.NextDouble() (0) | 2025.01.15 |
C# Nullablity , Null 체크, NullReferenceException (0) | 2025.01.14 |