0
点赞
收藏
分享

微信扫一扫

需求: java数组索引偶数之和

Xin_So 2022-01-09 阅读 38

1.实现代码

/**
 * 需求: 求数组索引偶数之和
 */
public class ArrayUtil {

    public static void getSum(int[] arr) {
        int count = 0;
        for(int index = 0; index < arr.length; index++) {
            // 求出索引是偶数的元素出来
            if(index % 2 == 0) {
                // 把求出索引是偶数的元素累计加起来
                count += arr[index];
            }
        }
        System.out.println(count);
    }
    public static void main(String[] args) {
        // 传递一个实际数组给getSum方法
        int[] arr = new int[]{20,5,8,10,90,60,80};
        ArrayUtil.getSum(arr);
    }
}

2.输出结果

举报

相关推荐

0 条评论