Program 3 : Matrix Multiplication
Develop a program to Multiply two Matrices of order n by n. Repeat the experiment for different values of n and plot a graph of the time taken versus n.
To multiply two n x n
matrices where:
The user inputs the size
n
(max 100).Two matrices are filled with random integers.
The matrices are multiplied using the standard triple loop method.
Version 1: Logic Only
c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 100
void fillMatrix(int matrix[MAX][MAX], int n) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix[i][j] = rand() % 10;
// Random numbers between 0-9
}
void displayMatrix(int matrix[MAX][MAX], int n, const char* name) {
printf("\nMatrix %s:\n", name);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%4d", matrix[i][j]);
printf("\n");
}
}
void multiplyMatrices(int A[MAX][MAX], int B[MAX][MAX], int C[MAX][MAX], int n) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
C[i][j] = 0;
for (int k = 0; k < n; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
int main() {
int A[MAX][MAX], B[MAX][MAX], C[MAX][MAX];
int n;
printf("Enter size of matrix (max %d): ", MAX);
scanf("%d", &n);
if (n > MAX || n <= 0) {
printf("Invalid size.\n");
return 1;
}
srand(time(NULL)); // Seed random number generator
fillMatrix(A, n);
fillMatrix(B, n);
multiplyMatrices(A, B, C, n);
displayMatrix(A, n, "A");
displayMatrix(B, n, "B");
displayMatrix(C, n, "C (A x B)");
return 0;
}
Version 2: With Timing
c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 100
void fillMatrix(int matrix[MAX][MAX], int n) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix[i][j] = rand() % 10;
}
void displayMatrix(int matrix[MAX][MAX], int n, const char* name) {
printf("\nMatrix %s:\n", name);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%4d", matrix[i][j]);
printf("\n");
}
}
void multiplyMatrices(int A[MAX][MAX], int B[MAX][MAX], int C[MAX][MAX], int n) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
C[i][j] = 0;
for (int k = 0; k < n; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
int main() {
int A[MAX][MAX], B[MAX][MAX], C[MAX][MAX];
int n;
clock_t start, end;
double cpu_time_used;
printf("Enter size of matrix (max %d): ", MAX);
scanf("%d", &n);
if (n > MAX || n <= 0) {
printf("Invalid size.\n");
return 1;
}
srand(time(NULL)); // Seed RNG
fillMatrix(A, n);
fillMatrix(B, n);
start = clock();
multiplyMatrices(A, B, C, n);
end = clock();
cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
displayMatrix(A, n, "A");
displayMatrix(B, n, "B");
displayMatrix(C, n, "C (A x B)");
printf("\nTime taken for multiplication: %.6f seconds\n", cpu_time_used);
return 0;
}