#include <stdio.h>

// Function to calculate the sum of the boundary elements of a 2D array int fun(int arr[][5], int rows, int cols) { int sum = 0;

// Sum of the elements in the first and last row
for (int i = 0; i < cols; i++) {
    sum += arr[0][i];                   // Add the element in the first row
    sum += arr[rows - 1][i];            // Add the element in the last row
}

// Sum of the elements in the first and last column
for (int i = 1; i < rows - 1; i++) {
    sum += arr[i][0];                   // Add the element in the first column
    sum += arr[i][cols - 1];            // Add the element in the last column
}
return sum;

}

int main() { int arr[4][5] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20} }; int sum = fun(arr, 4, 5); printf("Sum of the boundary elements of the 2D array: %d\n", sum); return 0; }

C 语言二维数组周边元素求和 - 代码详解

原文地址: https://www.cveoy.top/t/topic/pyB6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录