ตัวอย่างการใช้ Array 2 มิติในการเก็บชั่วโมงในการใช้ Internet ของนักเรียน 3 คน และนำมาคำนวน
void setup(){
int[][] StdHrsInternetWeek =
{{3,4,5,6,5,4,3},
{2,1,4,7,2,1,3},
{7,8,9,5,10,6,5}};
PrintStdHrs(StdHrsInternetWeek);
PrintAvgHrsPerDay(StdHrsInternetWeek);
}
void PrintStdHrs(int[][] A){
for(int i=0;i<A.length;i++){
println("Total student"+i+"'s internet hrs = "+SumRow(A[i])+" , Average per day = "+AvgRow(A[i]));
}
}
int SumRow(int[] a){
int sum = 0;
for(int i=0;i<a.length;i++){
sum = sum + a[i];
}
return sum;
}
float AvgRow(int[] a){
float avg = (float)SumRow(a)/a.length;
return avg;
}
void PrintAvgHrsPerDay(int[][] A){
String[] day = {"Mondays","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
for(int i=0;i<A[0].length;i++){
println("Average "+day[i]+" = "+AvgColumn(A,i));
}
}
int SumColumn(int[][] a,int n){
int sum=0;
for(int i=0;i<a.length;i++){
sum = sum + a[i][n];
}
return sum;
}
float AvgColumn(int[][] a,int n){
float avg = (float)SumColumn(a,n)/a.length;
return avg;
}