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

คำนวณผลรวมทุกองค์ประกอบในอาร์เรย์ 2 มิติ ด้วยภาษา C


ปัญหา

คำนวณผลรวมขององค์ประกอบทั้งหมดในอาร์เรย์ 2 มิติ โดยใช้การกำหนดค่าเริ่มต้นระหว่างรัน (Run-time Initialization)

วิธีแก้

อาร์เรย์ 2 มิติ ใช้เมื่อต้องจัดเก็บตารางค่า หรือในการประยุกต์เมทริกซ์

ไวยากรณ์มีดังนี้:

datatype array_name [rowsize] [columnsize];

ตัวอย่าง: int a[4][4];

จำนวนองค์ประกอบ = rowsize * columnsize = 4*4 = 16

ตัวอย่าง

โปรแกรม C คำนวณผลรวมองค์ประกอบคู่และคี่ในอาร์เรย์ 2 มิติ 4x3 ด้วยการกำหนดค่าเริ่มต้นระหว่างรัน:

#include <stdio.h>

void main() {
    // ประกาศอาร์เรย์และตัวแปร //
    int A[4][3], i, j, even = 0, odd = 0;
    
    // อ่านองค์ประกอบเข้าไปในอาร์เรย์ //
    printf("Enter elements into the array A :\n");
    for(i = 0; i < 4; i++) {
        for(j = 0; j < 3; j++) {
            printf("A[%d][%d] : ", i, j);
            scanf("%d", &A[i][j]);
        }
    }
    
    // คำนวณผลรวมองค์ประกอบคู่และคี่ในอาร์เรย์ด้วยลูป for //
    for(i = 0; i < 4; i++) {
        for(j = 0; j < 3; j++) {
            if((A[i][j]) % 2 == 0) {
                even = even + A[i][j];
            } else {
                odd = odd + A[i][j];
            }
        }
    }
    
    printf("Sum of even elements in array A is : %d\n", even);
    printf("Sum of odd elements in array A is : %d", odd);
}

ผลลัพธ์

เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:

Enter elements into the array A:
A[0][0] : 01 A[0][1] : 02 A[0][2] : 03
A[1][0] : 04 A[1][1] : 10 A[1][2] : 20
A[2][0] : 30 A[2][1] : 40 A[2][2] : 22
A[3][0] : 33 A[3][1] : 44 A[3][2] : 55

Sum of even elements in array A is: 172
Sum of odd elements in array A is: 92