# Python program to print the Boundary elements of a Matrix

## Boundary Elements of a Matrix

The elements that are not surrounded by any other elements that belong to the same matrix are known as Boundary elements. Using this phenomena, we can build a program. Let us consider an Input output scenario and then construct a program.

### Input Output Scenario

Consider a matrix ( square matrix )

• The Boundary elements are the elements except the middle elements of the matrix.

• The middle element(s) of the matrix is 5 and there are no other middle elements except 5.

• So, the Boundary elements are 9, 8, 7, 6, 4, 3, 2, and 1 as they are lying in the boundary positions of the matrix.

9  8  7
6  5  4
3  2  1


### Algorithm

• Step 1 − Starting from the initial element of the matrix, traverse the elements of the array, which represents a matrix.

• Step 2 − We traverse the elements of the matrix by using two dimensional array in which one dimension represents the row and the other represents the column. So, the outer loop denotes the row of the matrix and the inner loop denotes the column of the matrix.

• Step 3 − If the element belongs to the first row or the last row or the first column or the last column, then that elements can be considered as a Boundary element and can be printed.

• Step 4 − If not, the element must be considered as a Non-boundary element and should be skipped. In such cases, a space should be printed instead of the Non-boundary element.

### Example

In the following example, we are going to discuss about the process of finding the boundary elements in a matrix.

def functionToPrint(arra, r, c):
for i in range(r):
for j in range(c):
if (i == 0):
print(arra[i][j])
elif (i == r-1):
print(arra[i][j])
elif (j == 0):
print(arra[i][j])
elif (j == c-1):
print(arra[i][j])
else:
print(" ")

if __name__ == "__main__":
arra = [[1, 2, 3, 4], [5, 6, 7, 8],
[9, 10, 11, 12], [13, 14, 15, 16]]

print("The boundary elements of the given matrix are: ")
functionToPrint(arra, 4, 4)


### Output

The output for the above program is as follows −

The boundary elements of the given matrix are:
1
2
3
4
5

8
9

12
13
14
15
16


Updated on: 08-May-2023

217 Views