반복하는 구문 반복문에는 어떠한 것들이 있을?
반복문에는 while, do~while, for, foreach이 있다.
조건이 true인 동안 반복을 수행하는 기본적인 반복문이다.
while(참 or 거짓)
{
반복 할 내용
}
int eatApple = 0;
while (eatApple < 10)
{
eatApple++;
Console.WriteLine($"{eatApple}번째로 사과를 먹습니다.");
}
Console.WriteLine("사과 {0}개까지 먹어서 배가 부르다.. 꺼어억", eatApple);
조건과 상관없이 최소 1번은 실행되는 반복문이다.
do
{
반복 할 내용
} while(참 or 거짓);
do
{
eatApple++;
Console.WriteLine($"일단은 {eatApple}번째로 사과를 먹습니다.");
} while (eatApple < 20);
Console.WriteLine("사과 {0}개까지 먹어서 배가 터지겠뜨아ㅏ....", eatApple);
가장 일반적인 반복문. 초기화, 조건, 증감 모두 한 줄에 표현된다.
for (초기화; 조건; 증감 or 처리)
{
반복 할 내용
}
for 순서 : 초반 한번만 (1 > 2 > 3 > 4), 이후 지속적으로 (2 > 3 > 4)
- int i 라는 변수를 선언과 즉시 초기화 진행
- i < students.Length 해당 조건이 맞는지 확인
- 조건이 맞았으니, 반복 할 내용 실행
- i++로 증감 or 처리 실행
string[] students = { "짱구", "철수", "맹구", "유리", "훈이" };
for (int i = 0; i < students.Length; i++)
{
Console.WriteLine($"{i + 1}번 학생 이름: {students[i]}");
}
int count = 0;
for (string name = students[count]; count < students.Length; name = (count < students.Length) ? students[count] : null)
{
Console.WriteLine($"{count + 1}번 학생 이름: {name}");
count++;
}
컬렉션(array, list 등)의 요소를 하나씩 순회할 때 사용된다.
foreach (var item in 컬렉션)
{
// 반복할 내용
}
string[] students = { "짱구", "철수", "맹구", "유리", "훈이" };
int count = 0;
foreach (string name in students)
{
Console.WriteLine($"{count + 1}번 학생 이름: {name}");
count++;
}
InvalidOperationException 발생 가능)| 반복문 | 특징 | 적합한 상황 |
|---|---|---|
while | 조건이 먼저 검사됨 | 반복 횟수 모를 때 |
do~while | 조건 없이 무조건 1회 실행 | 최소 1회 실행 보장 |
for | 인덱스를 사용해 요소 제어 가능 | 배열, 인덱스 기반 루프 |
foreach | 읽기 전용 순회, 요소 직접 수정 불가 | 컬렉션 탐색용 (읽기 전용) |