Python Program to Add Two Matrices Using Nested Loop

Python Program to Add Two Matrices Using Nested Loop | Here, we will develop a Python program to add two matrices using nested loop. For adding any two matrices, both the matrices should be of the same dimension; we carry out the addition by adding corresponding elements together. Similar to the add operation, we can also implement other mathematical operations.

Add Two Matrices using Nested Loop in Python

A nested loop is a loop inside another loop. In this example, we use nested for-loops to add matrices.

Program description:- Write a python program to add two matrices using nested loop

# Python program to add two matrices using nested loop

r = int(input("Enter the rows: "))
c = int(input("Enter the columns: "))

print("Enter Matrix 1: ")
m1 = [[int(input()) for i in range(c)] for i in range(r)]
print("Matrix 1 is: ")
for n in m1:
   print(n)

print("Enter Matrix 2: ")
m2 = [[int(input()) for i in range(c)] for i in range(r)]
for n in m2:
   print(n)

r = [[0 for i in range(c)] for i in range(r)]
for i in range(len(r)):
   for j in range(c):
      r[i][j] = [m1[i][j] + m2[i][j]]
print("Add Matrix: ")
for i in r:
   print(i)

Output:-

Enter the rows: 2
Enter the columns: 3
Enter Matrix 1:
12
25
23
10
24
30
Matrix 1 is:
[12, 25, 23]
[10, 24, 30]
Enter Matrix 2:
25
36
42
10
15
20
[25, 36, 42]
[10, 15, 20]
Add Matrix:
[[37], [61], [65]]
[[20], [39], [50]]

In the above code, we have used a nested for loop to add m1 and m2. The outer loop reads the row elements the inner loop reads the column elements and stores the result in r.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Python List Program Examples With Output

Leave a Comment

Your email address will not be published. Required fields are marked *