陣列元素的 Java 程式乘法


查詢陣列元素的乘積。

  • 建立一個空變數。(乘積)
  • 將其初始化為 1。
  • 在一個迴圈中遍歷每個元素(或從使用者那裡獲取每個元素),將每個元素乘以乘積。
  • 列印乘積。

示例

 現場演示

import java.util.Arrays;
import java.util.Scanner;
public class ProductOfArrayOfElements {
   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 product = 1;
      System.out.println("Enter the elements of the array one by one ");
      for(int i=0; i<size; i++){
         myArray[i] = s.nextInt();
         product = product * myArray[i];
      }
      System.out.println("Elements of the array are: "+Arrays.toString(myArray));
      System.out.println("Sum of the elements of the array ::"+product);
   }
}

輸出

Enter the required size of the array:
5
Enter the elements of the array one by one
11
65
22
18
47
Elements of the array are: [11, 65, 22, 18, 47]
Sum of the elements of the array:13307580

更新於:18-6-2024

18K+ 檢視次數

開啟您的 職業生涯

完成課程,獲取認證

開始吧
廣告
© . All rights reserved.