2012年5月31日 星期四

Java Basic(29)-Summing Elements of Arrays


class apples{
public static void main(String args[]){
int bucky[]={21,16,86,21,3};
int sum=0;
for(int counter=0;counter<bucky.length;counter++){ 使用循環計算
sum+=bucky[counter];  →添加陣列元素
}
System.out.println("the sum of these number is " + sum);
}
}



添加數組元素是指使用循環添加:
bucky[0] + bucky[1] + bucky[2] + bucky[3] + bucky[4] = 21+16+86+21+3=147

Program將運行這樣的:
the sum of these number is 147

沒有留言:

張貼留言