The first for loop is used to calculate the sum of the top row and the bottom row of the matrix, and the second for loop is used to calculate the sum of the elements in the leftmost column and the rightmost column except the two elements. Finally, the two summations are added together to obtain the sum of the surrounding elements.
〔Source program〕
#include
#include
#define M 4
#define N 5
int fun(int a[M][N])
{int sum=0,i;
for(i=0;i sum =a[0][i] a[M-1][i]; for(i=1;i sum =a[i][0] a[i][N-1]; return sum ; } main() { int aa[M][N]={{1,3,5,7,9}, {2,9,9,9,4}, {6,9,9,9,8}, {1,3,5,7,0}}; int i,j,y; clrscr(); printf("The original data is :\\n"); for(i=0;i {for(j=0;j printf("\\n"); } y=fun(aa); printf("\\nThe sum: %d\\n",y); printf("\\n"); } private function Anyl(A()() AS INTEGER,byval m as integer,byval n as integer) as long tol=sum_side(A,m,n) print tol if m=n then sd=Diag(A,m) sid=InDiag(A,m) print sd print sid else print "m≠n" end if end function private function Sum_side(A()() AS INTEGER,byval m_side as integer,byval n_side as integer) as long dim sum as long sum=0 n_side=n_side-1 for i=0 to n step 1 sum=sum A(0)(i) next i m=m-2 for i=1 to m step 1 sum=sum A(i)(0) sum=sum A(i)(n) next i m=m 1 for i=0 to n step 1 sum=sum A(m)(i) next i sum_side=sum end function private function Diag(A()() AS INTEGER,byval m as integer) as long dim Sum_Diag as long m=m-1 Sum_Diag=0 FOR i=0 to m step 1 Sum_Diag=Sum_Diag A(i)(i) next i Diag=Sum_Diag end function private function InDiag(A()() AS INTEGER,byval m as integer) as long dim Sum_InDiag as long m=m-1 Sum_Diag=0 FOR i=0 to m step 1 Sum_InDiag=Sum_InDiag A(i)(m-i) next i InDiag=Sum_InDiag end functionSum of edge elements of two-dimensional array
The above is the detailed content of Returns the sum of the surrounding elements of the two-dimensional array as the function value. For more information, please follow other related articles on the PHP Chinese website!