# For Loop (C#)

## 迴圈基礎

### 範例程式

{% embed url="<https://1drv.ms/u/s!AjMRvW84HYeNgawEFKotORH1_mNlVw?e=7PY5uJ>" %}

```csharp
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public GameObject SpherePrefab;

    void Start()
    {
        float length = 1.5f;
        int count = 5;

        for (int j = 0; j < count; j++)
        {
            for (int i = 0; i < count; i++)
            {
                GameObject go = Instantiate(SpherePrefab);
                go.transform.position = new Vector3(i * length - count / 2 * length,0 ,j * length - count / 2 * length);
            }
        }
    }
}

```

### 執行結果ˇ

<figure><img src="https://1557561871-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSIq643mEVz2djjDy9515%2Fuploads%2F8sz8Rz3Lnajr5cMMaSXH%2Fimage.png?alt=media&#x26;token=b8cfc570-d3c0-449d-a37c-7b2791c283ba" alt=""><figcaption></figcaption></figure>

## 迴圈謎題練習

<figure><img src="https://1557561871-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSIq643mEVz2djjDy9515%2Fuploads%2FrgzjslBJtS75lnTosX6p%2Fimage.png?alt=media&#x26;token=f07b5f7c-c967-4f14-b03f-b7216d231f31" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
試著修改劃紅線的程式碼，去解以下題目。
{% endhint %}

### 題目1

<figure><img src="https://1557561871-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSIq643mEVz2djjDy9515%2Fuploads%2Fxp9hf9uqMmJiO8NOsWob%2Fimage.png?alt=media&#x26;token=0c1f59ab-d204-46d6-818b-c717c89a3133" alt=""><figcaption></figcaption></figure>

### 參考答案

```csharp
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public GameObject SpherePrefab;

    void Start()
    {
        float length = 1.5f;
        int count = 5;

        for (int j = 0; j < count; j++)
        {
            for (int i = 0; i <= j; i++)
            {
                GameObject go = Instantiate(SpherePrefab);
                go.transform.position = new Vector3(i * length - count / 2 * length,0 ,j * length - count / 2 * length);
            }
        }
    }
}
```

### 題目2

<figure><img src="https://1557561871-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSIq643mEVz2djjDy9515%2Fuploads%2FF2iB9CqIxmJ5bBozD6xy%2Fimage.png?alt=media&#x26;token=3d6de59a-0744-4534-b893-bfc440d80af2" alt=""><figcaption></figcaption></figure>

### 題目3

<figure><img src="https://1557561871-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSIq643mEVz2djjDy9515%2Fuploads%2FMEyIDSOXYpmEMdA4IDEP%2Fimage.png?alt=media&#x26;token=364e4c3d-e192-4030-be64-2215798f6d8c" alt=""><figcaption></figcaption></figure>

### 題目4

<figure><img src="https://1557561871-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSIq643mEVz2djjDy9515%2Fuploads%2F12KdebykG8h3TpfLxENY%2Fimage.png?alt=media&#x26;token=5b84b835-49c7-46e0-875f-879640a029cf" alt=""><figcaption></figcaption></figure>
