C++ 程式用於陣列元素相乘


給定一個整數元素陣列,任務是將陣列的元素相乘並顯示它。

示例

Input-: arr[]={1,2,3,4,5,6,7}
Output-: 1 x 2 x 3 x 4 x 5 x 6 x 7 = 5040
Input-: arr[]={3, 4,6, 2, 7, 8, 4}
Output-: 3 x 4 x 6 x 2 x 7 x 8 x 4 = 32256

下面程式中用到的方法如下 -

  • 初始化臨時變數以將最終結果儲存為 1
  • 從 0 到 n 開始迴圈,其中 n 是陣列的大小
  • 不斷將 temp 的值與 arr[i] 相乘以得到最終結果
  • 顯示 temp 的值,該值將是結果值

以下是將輸入相乘並生成所需輸出的示例

演算法

Start
Step 1-> Declare function for multiplication of array elements
   int multiply(int arr[], int len)
      set int i,temp=1
         Loop For i=0 and i<len and i++
            Set temp=temp*arr[i]
         End
         return temp
step 2-> In main()
   Declare int arr[]={1,2,3,4,5,6,7}
      Set int len=sizeof(arr)/sizeof(arr[0])
      Set int value = multiply(arr,len)
      Print value
Stop

示例

 即時演示

#include<stdio.h>
//function for multiplication
int multiply(int arr[], int len) {
   int i,temp=1;
   for(i=0;i<len;i++) {
      temp=temp*arr[i];
   }
   return temp;
}
int main() {
   int arr[]={1,2,3,4,5,6,7};
   int len=sizeof(arr)/sizeof(arr[0]);
   int value = multiply(arr,len);
   printf("value of array elements after multiplication : %d",value);
   return 0;
}

輸出

如果執行以上程式碼,將生成以下輸出

value of array elements after multiplication : 5040

更新於: 2019 年 10 月 18 日

7K+ 次瀏覽

啟動你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.