Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C Program to print the sum of boundary elements of a matrix
In C programming, finding the sum of boundary elements of a matrix involves identifying elements that are on the first row, last row, first column, or last column. Boundary elements form the outer edge of the matrix.
Syntax
for(i = 0; i < rows; i++){
for(j = 0; j < cols; j++){
if(i == 0 || i == rows-1 || j == 0 || j == cols-1){
// This is a boundary element
}
}
}
Example
Consider a 3x3 matrix to understand boundary elements −
Given Matrix
1 2 3 4 5 6 7 8 9
Boundary Elements
1 2 3 4 6 7 8 9
Sum of boundary elements: 1 + 2 + 3 + 4 + 6 + 7 + 8 + 9 = 40
Complete Program
Here is a complete C program to find and display the sum of boundary elements −
#include <stdio.h>
int main() {
int rows = 3, cols = 3;
int mat[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int sum = 0;
int i, j;
printf("Original Matrix:<br>");
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
printf("%d ", mat[i][j]);
}
printf("<br>");
}
printf("\nBoundary Matrix:<br>");
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
if(i == 0 || j == 0 || i == rows-1 || j == cols-1) {
printf("%d ", mat[i][j]);
sum += mat[i][j];
}
else {
printf(" ");
}
}
printf("<br>");
}
printf("\nSum of boundary elements: %d<br>", sum);
return 0;
}
Original Matrix: 1 2 3 4 5 6 7 8 9 Boundary Matrix: 1 2 3 4 6 7 8 9 Sum of boundary elements: 40
How It Works
The algorithm checks each element's position using these conditions:
- First Row: i == 0
- Last Row: i == rows-1
- First Column: j == 0
- Last Column: j == cols-1
If any condition is true, the element is on the boundary and gets added to the sum.
Conclusion
Finding boundary elements involves checking if an element is on the outer edge of the matrix. This technique is useful in image processing and matrix operations where edge elements need special handling.
