#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 +=
#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
funtakes a 2D arrayarr, number of rowsrows, and number of columnscolsas parameters. - It initializes the variable
sumto 0. - The first
forloop calculates the sum of the elements in the first and last row of the array by iterating over the columns. - The second
forloop 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
mainfunction, a 2D arrayarris defined and initialized. - The function
funis called with the arrayarr, number of rows 4, and number of columns 5. - The calculated sum is printed
原文地址: https://www.cveoy.top/t/topic/hPuv 著作权归作者所有。请勿转载和采集!