
👇코드예제
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
for (int i = 0; i < 10; i++)
{
Debug.Log(i);
}
}
}
// i는 0으로 값이 초기화되며, i < 10 조건을 검사한다.
// 조건이 참이기 때문에 Debug.Log(i);를 실행해 0을 출력한다
// i++로 index는 1이 되고, index < 10 조건을 검사한다.
// 반복문 내부로 가서 Debug.Log(i); 를 실행해 1을 출력한다.
// ...
// 9를 출력하고 i가 10이 되어 index < 10을 만족하지 않게 되면 반복문을 종료한다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
for (int x = 1; x < 10; x ++)
{
for ( int y = 1; y < 10; y ++)
{
Debug.Log($"{x} x {y} = {x * y}");
}
}
}
}
// 바깥쪽 for 문이 x = 1부터 x = 9까지 9번이고,
// 안쪽 for 문이 y = 1부터 y = 9까지 9번이기 때문에
// 안쪽 for문 내부에 있는 23번째 줄은 89번(9*9) 실행된다.
// 즉, 구구단이 출력된 모습을 볼 수 있다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
int i = 0;
void Start()
{
while ( i < 10 )
{
Debug.Log(i);
i++;
}
}
}
☝ 그림과 같이 for문과 while 문의 차이점은 변수선언 및 초기화와 증감연산자의 위치가 다르다
👇코드예제
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
int i = 0;
void Start()
{
do
{
Debug.Log(i);
i++;
} while (i < 10);
}
}
👇 무한 루프 사용 방법
for 반복문은 세미콜론 사이에 들어가는 문장을 작성하지 않으면 되고, while, do-while은 조건에 true 를 작성해 조건이 계속 참이도록 설정
흐름을 끊고 프로그램의 실행 위치를 원하는 곳으로 이동시킨다
break
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
for (int i = 0; i < 10; i++)
{
if ( i == 5)
{
break;
}
Debug.Log(i);
}
}
}
// break 는 현재 실행준인 반복문의 실행을 중단하기 때문에
// i 가 5가 되면 반복문을 종료한다.
// 결과는 0, 1, 2, 3, 4까지만 출력된다.
continue
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
for (int i = 0; i < 10; i++)
{
if ( i == 5)
{
continue;
}
Debug.Log(i);
}
}
}
// index가 5인 조건만 건너뛰고, 반복문 자체를 종료 시키지는 않는다.
// 결과는 0, 1, 2, 3, 4, 6, 7, 8, 9가 출력된다.
goto
return