本程序计算数组中所有元素的和。
代码1:数组元素由程序内部初始化
/** * @author: 理工云课堂 * @description: 求数组元素的和 */ class SumOfArray{ public static void main(String args[]){ int[] array = {10, 20, 30, 40, 50, 10}; int sum = 0; //Advanced for loop for( int num : array) { sum = sum+num; } System.out.println("Sum of array elements is:"+sum); } }
输出:
Sum of array elements is:160
代码2:数组元素由用户输入
/** * @author: 理工云课堂 * @description: 用户输入10个数组元素值 */ import java.util.Scanner; class SumDemo{ public static void main(String args[]){ Scanner scanner = new Scanner(System.in); int[] array = new int[10]; int sum = 0; System.out.println("Enter the elements:"); for (int i=0; i<10; i++) { array[i] = scanner.nextInt(); } for( int num : array) { sum = sum+num; } System.out.println("Sum of array elements is:"+sum); } }
输出:
Enter the elements: 1 2 3 4 5 6 7 8 9 10 Sum of array elements is:55