Java程序找到数组元素之和的示例
要找到数组元素之和。
- 创建一个空变量(sum)。
- 在循环中将其初始化为0。
- 遍历每个元素(或从用户获取每个元素),将每个元素加到sum。
- 打印sum。
示例
import java.util.Arrays;
import java.util.Scanner;
public class SumOfElementsOfAnArray {
public static void main(String args[]){
System.out.println("Enter the required size of the array :: ");
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one ");
for(int i=0; i<size; i++){
myArray[i] = s.nextInt();
sum = sum + myArray[i];
}
System.out.println("Elements of the array are: "+Arrays.toString(myArray));
System.out.println("Sum of the elements of the array ::"+sum);
}
}
输出
Enter the required size of the array ::
5
Enter the elements of the array one by one
45
12
55
78
445
Elements of the array are: [45, 12, 55, 78, 445]
Sum of the elements of the array ::635