C#
반복문
코다람쥐
2022. 1. 22. 21:24
1. while문
using System;
namespace CSharp
{
class Program
{
static void Main(string[] args)
{
int a = 0;
while (a < 10)
{
Console.WriteLine("{0}", a);
a++;
}
}
}
}
while(조건) { } 형식으로 쓸 수 있다.
위 코드는 a값이 1씩증가하면서 a값을 출력하는 코드이다.
2. do while문
do while문은 조건에 관계없이 무조건 1번은 실행하고 그 이후에 조건을 살펴보면서 while문처럼 동작한다.
주의할점은 while문과 다르게 마지막에 세미콜론(;)으로 닫아줘야한다.
using System;
namespace CSharp
{
class Program
{
static void Main(string[] args)
{
int a = 11;
do
{
Console.WriteLine("{0}", a); // 11출력
a++;
}while (a < 10);
}
}
}
3. for문
for문의 형식은
for(초기화식 : 조건식 : 반복식)으로 선언된다.
using System;
namespace CSharp
{
class Program
{
static void Main(string[] args)
{
for(int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
}
}