Unity 기본4 - 반복문 while, for문

특정 조건을 만족할때, 원하는 명령을 반복하도록 하는 명령

 

1. while

 

특정 조건을 만족하는 동안 반복문 실행

 

while (조건문) {조건문이 참일때 실행}

 

if문 처럼 조건문이 참일 때 실행하는 문장이 1문장이면, {}는 생략 가능하나, 쓰는게 좋다

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int i = 0;

        while (i < 10)
        {
            Debug.Log(i);
            i += 2;
        }

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

i < 10인 동안, {}내의 문장을 반복 실행

 

i < 10을 체크

 

Debug.Log(i);로 i 출력

 

i += 2; 하고 나서, 

 

다시 i < 10을 체크

 

 

 

 

 

2. do while

 

do

{

(조건이 참이면 실행)

}

while (조건);

 

do {}에 있는 문장은, while 의 조건문이 참이든 거짓이든 관계없이 무조건 1번 실행

 

실행하고 나서, while의 조건문 비교하여 조건이 참이면 do에 있는 문장을 반복 실행

 

주의할 부분은 while(조건) 다음에 ;으로 끝내야한다

 

 

 

 

 

 

do while은 많이 쓰지는 않는다

 

while로 할 수 있기 때문

 

 

3. break & continue

 

break;는 반복문 내에서 조건을 만족하면 반복문을 강제로 중단시키고 탈출하는 명령

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        float thickness = 0.0001f;
        int count = 0;

        while (thickness <= 1)
        {
            count++;
            thickness *= 2;

            if (thickness > 0.5f)
            {
                break;
            }
        }

        Debug.Log(count + "번 접었습니다.");
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

참고로 int count와 string인 "번 접었습니다."를 더하면 count를 string으로 생각해서 그대로 붙여줌

 

파이썬은 안되는거

 

 

 

 

 

continue;는 조건을 만족하면 continue 이후의 문장들은 모두 스킵하고 처음부터 반복문을 다시 시작함

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        float thickness = 0.0001f;
        int count = 0;

        while (thickness <= 1)
        {
            count++;
            thickness *= 2;

            if (thickness > 0.1f)
            {
                continue;
            }
            Debug.Log(count + "번 접었습니다.");
        }

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

9번 접었습니다 이후에 0.1f보다 커져서, 그 이후는 출력을 모두 스킵하고,

 

반복문 탈출하고 나서 마지막 한번 출력

 

 

 

 

4. 무한 반복

 

while (true) {}로 무한반복문 가능

 

조건이 true니까 항상 실행

 

unity에서는 사용하지 않을 것을 권고함

 

무한반복문에 취약하다고 함

 

 

5. for문

 

for (initializer ; condition ; iterator) {condition이 참이면 실행}

 

initializer에서 선언한 변수는 for문 내 {}에서만 사용

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //중괄호 안에서만 사용할 변수 i를 새로 선언
        for (int i = 0; i < 10; i++)
        {
            Debug.Log(i);
        }

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

i = 0부터 시작해서(initial), i < 10인 동안(check condition), i를 1씩 증가(iterator)시키면서 i를 출력

 

>  i = 0,1,2,3,..,9일때 출력

 

 

 

 

 

6. 연습문제1

 

1보다 큰 수 a,b에 대하여 a에 b를 몇번 곱하면 1000을 넘는지 계산하는 프로그램

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int a = 3;
        int b = 7;
        int count = 0;

        while (a <= 1000)
        {
            a *= b;
            count++;
        }
       
        Debug.Log(count);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

 

 

7. 연습문제2

 

첫 줄에 *이 1개

 

두번째 줄에 *이 3개

 

세번째 줄에 *이 5개

 

....

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
        for (int i = 1; i < 20; i++)
        {
            string star = "";

            if (i % 2 == 0)
            {
                continue;
            }

            for (int j = 0; j < i; j++)
            {
                star += "*";
            }

            Debug.Log(star);
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

 

8.연습문제 3

 

구구단을 2단부터 9단까지 출력하는 프로그램

 

int와 string의 덧셈은 int를 string으로 바꿔서 그대로 붙여준다는 것을 이용

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
        for (int i = 2; i < 10; i++)
        {
            for (int j = 1; j<10; j++)
            {
                Debug.Log(i + " x " + j + " = " + i * j);
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

TAGS.

Comments