Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ คูณสมาชิกในอาร์เรย์


บทนำ

กำหนดอาร์เรย์จำนวนเต็ม ต้องการคูณสมาชิกทั้งหมดในอาร์เรย์และแสดงผล

ตัวอย่าง

  • arr[] = {1,2,3,4,5,6,7} → 1×2×3×4×5×6×7 = 5040
  • arr[] = {3,4,6,2,7,8,4} → 32256

แนวคิด

  1. กำหนดตัวแปร temp = 1
  2. วนลูป i=0 ถึง n-1: temp = temp × arr[i]
  3. แสดงค่า temp

ตัวอย่างโค้ด C++

#include <stdio.h>

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