# 函數傳遞陣列

### 一、傳遞一維陣列

> 要傳遞一維陣列到函數裡，只要指名傳入的引數是一個陣列即可。

```
public class ch07_5 {

	public static void main(String[] args) {
		int score[]={9,14,6,18,2,10};
		largest(score);
	}

	public static void largest(int arr[]){
		int max=arr[0];
		for(int i=0; i<arr.length; i++)
			if(max<arr[i])
				max=arr[i];
		System.out.println("largest num = "+max);

	}
}
```

OUTPUT：\
largest num = 18

{% hint style="info" %}
如果要傳遞陣列到函數裡，只要在函數內填上陣列的名稱即可。

如以上範例的第五行：

```
largest(score);
```

{% endhint %}

### 二、傳遞二維陣列

```
public class ch07_6 {

	public static void main(String[] args) {
		int score[][]={{9,14,6,18,2,10},{18,32,65,27,30,17}};
		largest(score);
	}

	public static void largest(int arr[][]){
		int max=arr[0][0];
		for(int i=0; i<arr.length; i++)
			  for(int j=0; j<arr[i].length; j++)
				  if(max<arr[i][j])
					  max=arr[i][j];
		System.out.println("largest num = "+max);

	}
}
```

OUTPUT：\
largest num = 65

在主程式main 當中，score函數改為二維函數；\
而相同在函數內填上陣列名稱；

在函數largest 中，記得改為接收二維陣列 （本範例為整數陣列，固宣告二維整數陣列）。

### 三、函數資料型態注意

{% hint style="info" %}
傳回陣列函數該注意的是：

如果為整數陣列，必須在函數前加上int\[]&#x20;

若是二維陣列則加上int\[]\[]，以此類推。
{% endhint %}

```
public class ch07_7 {

	public static void main(String[] args) {
		int a[]={9,14,6,18,2,10};
		int b[];
		b=add5(a);
		for(int i=0; i<a.length; i++)
			System.out.print(b[i]+" ");
		System.out.println();
	}

	public static int[] add5(int arr[]){
		for(int i=0; i<arr.length; i++)
			arr[i]+=5;
		return arr;
	}

}
```

OUTPUT： \
14 19 11 23 7 15


---

# 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-07/java-07-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.
