본문 바로가기
Unity/C# 문법

[유니티 C#] 문법(반복문)

by Skull Crusher 2021. 4. 23.
728x90

1. 반복문

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

/*
 * [반복문]
 *  -> 연속적으로 반복 실행시키려는 코드 영역이 있을 때 사용하는 문법
 *
 * [종류]
 * for, while, do while
 * 
 * [for 반복문]
 * 
 * for (반복변수초기화; 반복조건; 반복변수연산)
 * {
 *      반복 실행이 필요한 코드들
 * }
 * 
 * for문 실행 순서
 * for (1; 2(T->반복, F->반복종료); 4->2)
 * {
 *      3
 * }
 * 
 * [while 반복문]
 * 
 * 반복변수초기화;
 * while (반복조건)
 * {
 *      반복 실행이 필요한 코드들
 *      반복변수연산;
 * }
 * 
 * 1
 * while (2(T->반복, F->반복종료)) {
 *      3
 *      4
 * }
 * 
 */

public class ForWhileLoop : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //Debug.Log("For 시작");
        //for (int i = 0; i < 5; i++)
        //{
        //    Debug.Log("반복변수 : " + i + ", 반복횟수 : " + (i + 1));
        //}
        //Debug.Log("For 종료");

        //Debug.Log("While 시작");
        //int i = 0;
        //while (i < 5)
        //{
        //    Debug.Log("반복변수 : " + i + ", 반복횟수 : " + (i + 1));
        //    i++;
        //}
        //Debug.Log("While 종료");

        // [퀴즈]
        // 1. For문을 사용해 10 -> 1까지 순서대로 출력하시오.
        // -> 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

        int i = 0;

        string result = "";
        for (i = 10; i >= 1; i--)
        {
            result += i.ToString();
            string comma = (i == 1) ? "" : ", ";
            result += comma;
        }
        Debug.Log(result);

        // 2. While문을 사용해서 1 ~ 10까지의 합을 구해서 출력하시오.
        // -> 1부터 10까지의 합은 ?? 입니다.

        i = 1;
        int sum = 0;
        while (i <= 10)
        {
            sum += i; // sum = sum + i;
            i++;
        }
        Debug.Log("1부터 10까지의 합은 " + sum + " 입니다.");


 






        // 3. For문을 사용해 1 ~ 10 중에 홀수만 출력해 보세요.
        // -> 1, 3, 5, 7, 9,

        result = "";
        for (i=1; i<10; i+=2)
        {
            result += i.ToString();
            string comma = (i == 9) ? "" : ", ";
            result += comma;
        }
        Debug.Log(result);

        // 4. 구구단 5단을 출력하시오.
        // -> 5*1=5, 5*2=10 .... 5*9=45
        // * 5(고정값) * n(반복변수사용) = (연산값)

        result = "";
        for (i = 1; i<=9; i++)
        {
            string gugudan = ("5 * " + i.ToString() + " = " + (5 * i));
            result += gugudan;
            string comma = (i == 9) ? "" : ", ";
            result += comma;
        }
        Debug.Log(result);

        // * 출력은 4줄로 출력해 주세요.

    }

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

댓글