C#/C#_기초강의
(C#) 반복문: while, do ~ while
코딩ABC
2023. 4. 22. 08:03
반응형
while 구문과 do~while 구문을 이용한 반복문에 대해서 설명합니다.
while 문
while문은 조건이 참(true)인 동안 반복합니다. 루프를 0번 이상 반복합니다.
do ~ while 문
do ~ while문은 조건이 참(true)인 동안 반복하며, 최소한 1 번 이상 루프를 반복합니다.
while 예제
static void Main(string[] args)
{
int i = 0;
while (i<10)
{
i++;
Console.Write($"{i} ");
}
Console.WriteLine();
}
(Output)
1 2 3 4 5 6 7 8 9 10
do ~ while 예제
위에서 작성한 1부터 10까지 출력하는 코드는 do ~ while 문으로 표현하면 다음과 같습니다.
static void Main(string[] args)
{
int i = 0;
do
{
i++;
Console.Write($"{i} ");
} while (i < 10);
Console.WriteLine();
}
(Output)
1 2 3 4 5 6 7 8 9 10
while 또는 do ~ while 문을 이용해서 무한 반복문을 만들기 위해서는 다음과 같이 하면 됩니다.
while(true) { // 무한 반복 } |
do { // 무한 반복 } while(true); |
break 명령어를 사용해서 무한 반복문을 벗어나게 할 수 있습니다.
반응형