Part of the series

Several example codes

~2 min read • Updated Oct 13, 2025

Program Overview

This Python program reads a 2D matrix and computes the product of all non-zero elements that are not on the border.
Border elements include the first and last rows and columns.


Python Code:


def read_matrix(rows: int, cols: int) -> list[list[int]]:
    print(f"Enter elements for a {rows}×{cols} matrix:")
    matrix = []
    for i in range(rows):
        row = list(map(int, input(f"Row {i+1}: ").strip().split()))
        if len(row) != cols:
            print("Each row must contain exactly the number of columns.")
            exit()
        matrix.append(row)
    return matrix

def product_of_inner_nonzero(matrix: list[list[int]]) -> int:
    rows = len(matrix)
    cols = len(matrix[0])
    product = 1
    found = False
    for i in range(1, rows - 1):
        for j in range(1, cols - 1):
            val = matrix[i][j]
            if val != 0:
                product *= val
                found = True
    return product if found else 0

def print_matrix(matrix: list[list[int]]):
    print("Input matrix:")
    for row in matrix:
        print("  ".join(str(val) for val in row))

# Read matrix dimensions
r = int(input("Number of rows: "))
c = int(input("Number of columns: "))
if r < 3 or c < 3:
    print("Matrix must be at least 3×3 to have inner elements.")
    exit()

# Read and process
mat = read_matrix(r, c)
print_matrix(mat)
result = product_of_inner_nonzero(mat)
print(f"\nProduct of non-border non-zero elements: {result}")

Sample Output:


Input matrix:  
12 11 10 9  
22 0 3 8  
32 4 2 7  
42 41 40 6  

Output:  
Product of non-border non-zero elements: 24

Written & researched by Dr. Shahin Siami