Home > Backend Development > C++ > C program to print the sum of matrix boundary elements

C program to print the sum of matrix boundary elements

WBOY
Release: 2023-09-15 15:53:02
forward
1180 people have browsed it

C program to print the sum of matrix boundary elements

Given a matrix, we need to print the bounding elements of the matrix and display their sum.

Example

Refer to the matrix given below -

Given matrix

1 2 3
4 5 6
7 8 9
Copy after login

Boundary matrix

1 2 3
4   6
7 8 9
Copy after login

Sum of boundary elements: 1 2 3 4 6 7 8 9 = 40

The logic of finding the sum of the boundary matrices is as follows-

for(i = 0; i<m; i++){
   for(j = 0; j<n; j++){
      if (i == 0 || j == 0 || i == n &ndash; 1 || j == n &ndash; 1){
         printf("%d ", mat[i][j]);
         sum = sum + mat[i][j];
      }
      else
         printf(" ");
      }
      printf("</p><p>");
}
Copy after login

Program

The following is used C program to print the sum of matrix boundary elements-

#include<stdio.h>
#include<limits.h>
int main(){
   int m, n, sum = 0;
   printf("</p><p>Enter the order of the matrix : ");
   scanf("%d %d",&m,&n);
   int i, j;
   int mat[m][n];
   printf("</p><p>Input the matrix elements</p><p>");
   for(i = 0; i<m; i++){
      for(j = 0; j<n; j++)
      scanf("%d",&mat[i][j]);
   }
   printf("</p><p>Boundary Matrix</p><p>");
   for(i = 0; i<m; i++){
      for(j = 0; j<n; j++){
         if (i == 0 || j == 0 || i == n &ndash; 1 || j == n &ndash; 1){
            printf("%d ", mat[i][j]);
            sum = sum + mat[i][j];
         }
         else
         printf(" ");
      }
      printf("</p><p>");
   }
   printf("</p><p>Sum of boundary is %d", sum);
}
Copy after login

Output

When the above program is executed, the following results are produced-

Enter the order of the matrix : 3 3
Input the matrix elements :
1 2 3
4 5 6
7 8 9
Boundary Matrix :
1 2 3
4 6
7 8 9
Sum of boundary is 40
Copy after login

The above is the detailed content of C program to print the sum of matrix boundary elements. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template