#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;
}

Explanation:

  • The function fun takes a 2D array arr, number of rows rows, and number of columns cols as parameters.
  • It initializes the variable sum to 0.
  • The first for loop calculates the sum of the elements in the first and last row of the array by iterating over the columns.
  • The second for loop calculates the sum of the elements in the first and last column of the array by iterating over the rows.
  • The function returns the total sum of the boundary elements.
  • In the main function, a 2D array arr is defined and initialized.
  • The function fun is called with the array arr, number of rows 4, and number of columns 5.
  • The calculated sum is printed
#includeint funint arr5 int rows int cols int sum = 0;复制代码for int i = 0; i cols; i++ sum += arr0i; sum += arrrows - 1i; for int i = 1; i rows - 1; i++ sum +=

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

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