# 迴圈

> 迴圈可以重複執行相同程式的片段，還可以讓程式結構化。\
> &#x20;這章學習如何利用不同的結構，撰寫更靈活，操作更方便。

迴圈包括 for、while、do while

### 一、for 迴圈

for迴圈：知道執行次數。

```
for(設定迴圈初值; 判斷條件; 設定增減量)
{
     迴圈主體;
}
```

![](/files/-M4glFQOF6P5Sr8vefek)

```
public class ch05_4 {

	public static void main(String[] args) {
		int i,sum=0;

		for(i=1; i<=10; i++)
			sum+=i;
		System.out.println("1+2+...+10= "+sum);

	}
```

OUTPUT：\
1+2+…+10= 55

#### 補充：在迴圈裡宣告的變數只是區域變數，跳出迴圈後，這個變數將不再使用。 透夠以下範例認識：

```
public static void main(String[] args) {
		int sum=0;

		for(int i=1; i<=3; i++) //在迴圈內宣告變數i
		{
			sum+=i;
			System.out.println("i="+i+", sum="+sum);
		}
	}
```

OUTPUT：\
i=1, sum=1\
i=2, sum=3\
i=3, sum=6

也可以同時宣告數個變數，並且給予初值；\
要注意的是，這些變數必須為相同的型態；\
換句話說：關鍵字只能出現一次。

```
for (int i=0,j=0; 判斷條件; 設定增減量)
```

### 二、while 迴圈

while 迴圈：無事先得知執行次數。

```
設定迴圈初值; 
while(判斷條件)
{
     迴圈主體;
     設定增減量;
}
```

{% hint style="info" %}
在while 迴圈中，通常判斷條件為邏輯運算子的運算式。
{% endhint %}

![](/files/-M4glduRsgNPgUujlnnl)

```
public class ch05_6 {

	public static void main(String[] args) {
		int n=0,sum=0;
		while(sum<20)
		{
			System.out.println("n="+n+", sum="+sum);
			n++;
			sum+=n;
		}

	}
```

OUTPUT：\
n=0, sum=0\
n=1, sum=1\
n=2, sum=3\
n=3, sum=6\
n=4, sum=10\
n=5, sum=15

### 三、do while 迴圈

**與while 不同在於，while會先判斷條件真假，而do while 是先執行後判斷真假**。\
因此至少會執行一次迴圈。

```
設定迴圈初值;
do
{
   迴圈主體;
   設定增減量;
}while(判斷條件)
```

![](/files/-M4glnH9knSLkLyybZlP)

```
import java.util.Scanner;
public class ch05_7 {

	public static void main(String[] args) {
		Scanner scn=new Scanner (System.in);
		int n,i=1,sum=0;

		do{
			System.out.print("請輸入值");
			n=scn.nextInt();
		}while (n<1); //輸入值要為大於0，否則將會一直印字串
		do
			sum+=i++; // 計算sum=sum+i, i值再加1
		while(i<=n);

		System.out.println("1+2+...+"+n+"="+sum);

	}
```

OUTPUT：\
請輸入值-1\
請輸入值-3\
請輸入值0  // 輸入 -1 -3 0 皆小於1 所以重複要求輸入\
請輸入值5  //5>1 條件正確\
1+2+…+5=15

### 四、巢狀迴圈

迴圈敘述中又有其他迴圈敘述。

#### 99乘法表

```
public static void main(String[] args) {
		int i,j;
		for (i=1; i<=9; i++)  //外迴圈
		{
			for (j=1; j<=9; j++)  //內迴圈
				System.out.print(i+"*"+j+"="+(i*j)+"\t");
			System.out.println();
		}

	}
```

![OUTPUT](/files/-M4glzH63wbj_105rhhB)


---

# 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://java.4-x.tw/java-05/java-05-2.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.
