函數傳遞陣列
一、傳遞一維陣列
要傳遞一維陣列到函數裡,只要指名傳入的引數是一個陣列即可。
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
二、傳遞二維陣列
OUTPUT: largest num = 65
在主程式main 當中,score函數改為二維函數; 而相同在函數內填上陣列名稱;
在函數largest 中,記得改為接收二維陣列 (本範例為整數陣列,固宣告二維整數陣列)。
三、函數資料型態注意
OUTPUT: 14 19 11 23 7 15
Last updated
Was this helpful?