Experiment 7 – Matrix Operations
Aim
To perform matrix operations (addition, subtraction, and multiplication) on two matrices using 2D arrays and nested loops in C programming. This experiment helps students understand 2D arrays, nested loop structures, and mathematical operations on matrices.
Through this experiment, students will learn to work with multidimensional arrays, implement matrix algorithms, validate matrix dimensions for operations, and understand the complexity of matrix multiplication.
Learning Outcomes
After completing this experiment, students will be able to:
- Declare and initialize 2D arrays (matrices)
- Read and display matrices using nested loops
- Understand matrix dimension requirements for different operations
- Implement matrix addition and subtraction (same dimensions required)
- Implement matrix multiplication (cols1 = rows2)
- Validate matrix dimensions before performing operations
- Use three nested loops for matrix multiplication
- Format matrix output for readability
Algorithm
The algorithm for matrix operations depends on the operation type. Here are the algorithms for each:
Matrix Addition/Subtraction Algorithm:
- Read dimensions (rows, cols) of both matrices
- Validate: rows1 == rows2 AND cols1 == cols2
- Read elements of matrix1 and matrix2
- For each position (i, j):
- Addition: result[i][j] = matrix1[i][j] + matrix2[i][j]
- Subtraction: result[i][j] = matrix1[i][j] - matrix2[i][j]
- Display result matrix
Matrix Multiplication Algorithm:
- Read dimensions: matrix1 (rows1 × cols1), matrix2 (rows2 × cols2)
- Validate: cols1 == rows2 (required for multiplication)
- Read elements of both matrices
- For each row i in matrix1 (0 to rows1-1):
- For each column j in matrix2 (0 to cols2-1):
- Initialize result[i][j] = 0
- For k from 0 to cols1-1:
- result[i][j] += matrix1[i][k] * matrix2[k][j]
- For each column j in matrix2 (0 to cols2-1):
- Result matrix dimensions: rows1 × cols2
- Display result matrix
Key Formula: For matrix multiplication, element result[i][j] is the dot product of row i of matrix1 and column j of matrix2.
Procedure
- Include
stdio.hheader file - Declare three 2D arrays:
matrix1,matrix2,result - Read dimensions (rows and columns) of matrices
- Read elements of both matrices using nested loops
- For Addition/Subtraction:
- Matrices must have same dimensions
- Add/subtract corresponding elements
- For Multiplication:
- Columns of first matrix = Rows of second matrix
- Use three nested loops: i, j, k
- result[i][j] = sum of (matrix1[i][k] * matrix2[k][j])
- Display result matrix using nested loops
Flowchart
START
│
├─→ Declare: matrix1[][], matrix2[][], result[][]
├─→ Read rows, cols
│
├─→ Read matrix1 elements (nested loops)
├─→ Read matrix2 elements (nested loops)
│
├─→ FOR i = 0 to rows-1
│ │
│ ├─→ FOR j = 0 to cols-1
│ │ │
│ │ ├─→ Addition: result[i][j] = matrix1[i][j] + matrix2[i][j]
│ │ └─→ Subtraction: result[i][j] = matrix1[i][j] - matrix2[i][j]
│ │
│ └─→ END FOR j
│
└─→ END FOR i
│
├─→ Display result matrix
│
└─→ END
For Multiplication:
FOR i = 0 to rows1-1
FOR j = 0 to cols2-1
result[i][j] = 0
FOR k = 0 to cols1-1
result[i][j] += matrix1[i][k] * matrix2[k][j]
END FOR k
END FOR j
END FOR iProgram Code
#include <stdio.h>
int main() {
int matrix1[10][10], matrix2[10][10], result[10][10];
int rows1, cols1, rows2, cols2, i, j, k;
int choice;
printf("Enter dimensions of first matrix (rows cols): ");
scanf("%d %d", &rows1, &cols1);
printf("Enter elements of first matrix:\n");
for (i = 0; i < rows1; i++) {
for (j = 0; j < cols1; j++) {
scanf("%d", &matrix1[i][j]);
}
}
printf("Enter dimensions of second matrix (rows cols): ");
scanf("%d %d", &rows2, &cols2);
printf("Enter elements of second matrix:\n");
for (i = 0; i < rows2; i++) {
for (j = 0; j < cols2; j++) {
scanf("%d", &matrix2[i][j]);
}
}
printf("\n1. Addition\n2. Subtraction\n3. Multiplication\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch(choice) {
case 1: // Addition
if (rows1 != rows2 || cols1 != cols2) {
printf("Error! Matrices must have same dimensions for addition.\n");
return 1;
}
for (i = 0; i < rows1; i++) {
for (j = 0; j < cols1; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
printf("\nResult of Addition:\n");
break;
case 2: // Subtraction
if (rows1 != rows2 || cols1 != cols2) {
printf("Error! Matrices must have same dimensions for subtraction.\n");
return 1;
}
for (i = 0; i < rows1; i++) {
for (j = 0; j < cols1; j++) {
result[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
printf("\nResult of Subtraction:\n");
break;
case 3: // Multiplication
if (cols1 != rows2) {
printf("Error! Columns of first matrix must equal rows of second matrix.\n");
return 1;
}
for (i = 0; i < rows1; i++) {
for (j = 0; j < cols2; j++) {
result[i][j] = 0;
for (k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
printf("\nResult of Multiplication:\n");
break;
default:
printf("Invalid choice!\n");
return 1;
}
// Display result matrix
int result_rows = rows1;
int result_cols = (choice == 3) ? cols2 : cols1;
for (i = 0; i < result_rows; i++) {
for (j = 0; j < result_cols; j++) {
printf("%d\t", result[i][j]);
}
printf("\n");
}
return 0;
}Sample Input and Output
Sample 1: Addition
Input:
Enter dimensions of first matrix (rows cols): 2 2 Enter elements of first matrix: 1 2 3 4 Enter dimensions of second matrix (rows cols): 2 2 Enter elements of second matrix: 5 6 7 8 1. Addition 2. Subtraction 3. Multiplication Enter choice: 1
Output:
Result of Addition: 6 8 10 12
Sample 2: Multiplication
Input:
Enter dimensions of first matrix (rows cols): 2 3 Enter elements of first matrix: 1 2 3 4 5 6 Enter dimensions of second matrix (rows cols): 3 2 Enter elements of second matrix: 7 8 9 10 11 12 1. Addition 2. Subtraction 3. Multiplication Enter choice: 3
Output:
Result of Multiplication: 58 64 139 154
Use Case / Real-world Relevance
Matrix operations are fundamental in many scientific and engineering applications:
- Computer Graphics: Transformations, rotations, scaling using matrix multiplication
- Machine Learning: Neural networks use matrix operations for forward and backward propagation
- Image Processing: Convolution operations, filters, and transformations
- Scientific Computing: Solving systems of linear equations, eigenvalue problems
- Game Development: 3D transformations, physics simulations, coordinate systems
- Cryptography: Encryption and decryption algorithms use matrix operations
- Data Analysis: Principal Component Analysis (PCA), dimensionality reduction
- Robotics: Kinematics calculations, coordinate transformations
Understanding 2D arrays and nested loops is crucial for working with matrices, which are essential data structures in advanced programming and computational mathematics. Matrix operations are fundamental in computer graphics, machine learning, scientific computing, and many other fields where mathematical computations are performed on structured data.
Viva Questions
Q1: What are the dimension requirements for matrix addition and subtraction?
Both matrices must have the same dimensions (same number of rows and same number of columns). For example, a 3×4 matrix can only be added or subtracted with another 3×4 matrix. The result will also be 3×4.
Q2: What are the dimension requirements for matrix multiplication?
The number of columns in the first matrix must equal the number of rows in the second matrix. If matrix1 is m×n and matrix2 is p×q, then n must equal p. The result will be m×q. For example, 2×3 × 3×4 = 2×4.
Q3: Why do we need three nested loops for matrix multiplication?
Three loops are needed: outer loop (i) for rows of result, middle loop (j) for columns of result, inner loop (k) to compute dot product. The inner loop multiplies each element of row i in matrix1 with corresponding element of column j in matrix2 and sums them up.
Q4: Is matrix multiplication commutative? (A × B = B × A?)
No, matrix multiplication is not commutative in general. A × B ≠ B × A (unless both are square and commute). Even dimensions may differ: if A is 2×3 and B is 3×4, then A×B is 2×4, but B×A is undefined (3×4 × 2×3 is invalid). Always check dimension compatibility.
Q5: What is the time complexity of matrix multiplication?
For two n×n matrices, naive multiplication is O(n³) because we have three nested loops each running n times. More efficient algorithms like Strassen's algorithm achieve O(n^2.81), but for learning purposes, the O(n³) algorithm is standard and easier to understand.
Q6: How do you access elements in a 2D array?
Use two indices: arr[row][col]. First index is row, second is column. Both start from 0. For a matrix declared as int matrix[10][10], valid indices are 0-9 for both dimensions.
Q7: Can we perform matrix operations without storing the entire matrix in memory?
For very large matrices, you might use sparse matrix representations (only store non-zero elements) or process elements on-the-fly without storing full matrices. However, for standard operations, storing matrices in 2D arrays is the most straightforward and efficient approach for matrices that fit in memory.
Q8: What happens if we try to multiply incompatible matrices?
Matrix multiplication is undefined if columns of first matrix ≠ rows of second matrix. The program should validate dimensions and display an error message. Attempting to multiply incompatible matrices would lead to incorrect results or array index out of bounds errors.
Related Links
🔹 Author: Dr. J. Siva Ramakrishna
🔹 Institution: Narayana Engineering College, Gudur
🔹 Last Updated: 9 January 2026