尋找陣列元素總和的 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

更新於: 14-6 月-2024

45K+ 瀏覽量

推動您的 職業發展

完成本課程即可獲得認證

開始學習
廣告
© . All rights reserved.