0% found this document useful (0 votes)
2 views2 pages

Matrix Multiplication Program

This document contains a C program for matrix multiplication. It prompts the user to input the dimensions and elements of two matrices, checks for compatibility, performs the multiplication, and displays the resultant matrix. The program includes error handling for incompatible matrix dimensions.

Uploaded by

Anubhav Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Matrix Multiplication Program

This document contains a C program for matrix multiplication. It prompts the user to input the dimensions and elements of two matrices, checks for compatibility, performs the multiplication, and displays the resultant matrix. The program includes error handling for incompatible matrix dimensions.

Uploaded by

Anubhav Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Matrix Multiplication Program

#include <stdio.h>

void main() {
int r1, c1, r2, c2;
int i, j, k;

// 1. Input dimensions of the first matrix


printf("Enter rows and columns for the first matrix:
");
scanf("%d %d", &r1, &c1);

// 2. Input dimensions of the second matrix


printf("Enter rows and columns for the second
matrix: ");
scanf("%d %d", &r2, &c2);

// 3. Validate dimension compatibility


if (c1 != r2) {
printf("Error! Column of first matrix must equal
row of second matrix.\n");
return 1; // Exit program with error code
}

int matrix1[r1][c1];
int matrix2[r2][c2];
int result[r1][c2];

// 4. Input elements for the first matrix


printf("\nEnter elements for Matrix 1:\n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix1[i][j]);
}
}
// 5. Input elements for the second matrix
printf("\nEnter elements for Matrix 2:\n");
for (i = 0; i < r2; i++) {
for (j = 0; j < c2; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix2[i][j]);
}
}

// 6. Perform matrix multiplication


for (i = 0; i < r1; i++) {
for (j = 0; j < c2; j++) {
result[i][j] = 0; // Initialize cell to zero
for (k = 0; k < c1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// 7. Display the result matrix


printf("\nResultant Multiplied Matrix:\n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c2; j++) {
printf("%d\t", result[i][j]);
}
printf("\n");
}

return 0;
}

You might also like