# 12.การทำงานซ้ำๆด้วย For

💬 ในหลายๆครั้งที่งานเราต้องทำซ้ำๆกันเดิม แต่มันอาจจะต้องมีการสร้างตัวแปรมาใช้ด้วย ซึ่งมันก็ใช้เพียงแค่ที่เดียว (คือใช้แล้วทิ้งตรงนั้นเลย) ทำให้เราเสียเวลาต้องคอยดูตัวแปรพวกนั้นด้วย ดังนั้นในบทนี้เราจะมาดูการทำงานซ้ำๆโดยใช้คำสั่ง **For loop statement** กันบ้างนะครับ

{% embed url="<https://www.youtube.com/watch?v=gJShvtB1QTI&list=PLUjAn8nwWnijERZ3HpzBk7NfSrau74_lQ&index=26>" %}

## 🎯 สรุปสั้นๆ

### 👨‍🚀 คำสั่ง For loop มาตรฐาน

```csharp
for( INITIALIZER; CONDITION; ITERATOR )
{
   // เข้ามาทำงานตรงนี้ถ้าเงื่อนไขยังเป็นจริงอยู่
}
```

การเขียน for ไม่จำเป็นต้องมี INITIALIZER ก็ได้นะ หรืออาจจะมีมากกว่า 1 ตัวก็ได้ เช่นโค้ดตัวอย่างด้านล่าง

```csharp
// แบบไม่มี initializer
for( ; round < 10; round++ )
{
  // Do something
}

// แบบมี initializer มากกว่า 1 ตัว
for( int a = 1, b = 2; round < 10; round++ )
{
  // Do something
}
```

เช่นเดียวกันตัว ITERATOR ก็ไม่จำเป็นต้องมีหรือจะมีกกว่า 1 อย่างก็ได้ เช่นโค้ดด้านล่าง

```csharp
for(int round = 0; round < 10; round++, a--)
{
   // Do something
}
```

และสุดท้าย CONDITION จะไม่ใส่ก็ได้ มันก็จะมองเป็น infinity loop ทันที

```csharp
for(int round = 0; ;round++)
{
   // Do something
}
```

{% hint style="info" %}
**เกร็ดความรู้**\
Infinity loop คือการทำงานในวงเล็บนั้นๆซ้ำไปเรื่อยๆไม่ไม่ทางจบการทำงาน ซึ่งสมัยโบราณเรานิยม loop ประเภทนี้ทำงานประเภท งานที่ต้องทำงานตลอดเวลา 24 ชม ไม่มีการหยุดพักเลย แต่ในปัจจุบันเราไม่นิยมเขียนโค้ดแบบนั้นแล้ว ซึ่งเราจะใช้ความสามารถของ cloud เข้ามาช่วย ซึ่งประสิทธิภาพจะดีกว่าการเขียนเป็น infinity loop มากครับ
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.saladpuk.com/beginner-1/csharp101/basic/for.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
