Complementary task for topic: 8
M Nemeth · 2023-08-29 15:21:04.629218'
Dynamic arrays: Matrix Addition
Dynamic arrays: Matrix Addition
HARD!
Create a C program that allows the user to input two matrices and performs addition on them using dynamic 2D arrays of floating-point numbers.
Example:
Enter the dimensions of matrix A (rows columns): 2 2
Enter the elements of matrix A:
1.2 3.4
5.6 7.8
Enter the dimensions of matrix B (rows columns): 2 2
Enter the elements of matrix B:
0.5 0.5
0.5 0.5
Resulting Matrix C (2x2):
1.700000 3.900000
6.100000 8.300000
Hint: Ask the user to input the dimensions of two matrices, matrix A and matrix B (rows and columns).
Allocate memory for the dynamic 2D arrays to store the elements of matrix A and matrix B based on their dimensions.
Ask the user to input the elements of matrix A and matrix B.
Perform matrix addition of A and B, and store the result in a new dynamic 2D array, matrix C.
Print the resulting matrix C.
Solution
Enter the dimensions of matrix A (rows columns): 2 2
Enter the elements of matrix A:
1.2 3.4
5.6 7.8
Enter the dimensions of matrix B (rows columns): 2 2
Enter the elements of matrix B:
0.5 0.5
0.5 0.5
Resulting Matrix C (2x2):
1.700000 3.900000
6.100000 8.300000
Explanation
In this task, we ask the user to input the dimensions of two matrices A and B, and allocate memory for dynamic 2D arrays matrixA, matrixB, and matrixC based on their dimensions. We use nested for loops to ask the user to input the elements of matrix A and matrix B, and store them in the dynamic arrays. We then perform matrix addition to calculate the resulting matrix C using two nested for loops, where each element of matrix C is the sum of the corresponding elements from matrix A and matrix B. Finally, we print the resulting matrix C and free the dynamically allocated memory for each matrix using free at the end of the program to avoid memory leaks.