2d Array - Prod - Add

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

1.

C program for matrix addition or addition of two 2-D arrays:

#include <stdio.h>
void main() {
int m,n;

// Input the dimensions of the arrays


printf("Enter the number of rows and columns for the arrays: ");
scanf("%d %d", &m, &n);

int matrix1[m][n], b[m][n], c[m][n];

// Input elements of the first array


printf("Enter elements of the first array:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}

// Input elements of the second array


printf("Enter elements of the second array:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &b[i][j]);
}
}

// Add corresponding elements of the two arrays


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}

// Display the result


printf("Resultant array after addition:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
}

2. C program for matrix multiplication or product of two 2-D arrays:

#include <stdio.h>
void main() {
int row1, col1, row2, col2;

// Input dimensions of the matrices


printf("Enter rows and columns of first array: ");
scanf("%d %d", &row1, &col1);
printf("Enter rows and columns of second array: ");
scanf("%d %d", &row2, &col2);

// Check if multiplication is possible


if (col1 != row2) {
printf("Array multiplication not possible. Columns of first array must be equal to rows of
second array.\n");
exit;
}

int a[row1][col1], b[row2][col2], c[row1][col2];

// Input elements of first array


printf("Enter elements of first matrix:\n");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) {
scanf("%d", &a[i][j]);
}
}

// Input elements of second array


printf("Enter elements of second array:\n");
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) {
scanf("%d", &b[i][j]);
}
}

// Initialize third array c to 0


for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
c[i][j] = 0;
}
}

// Matrix multiplication
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
for (int k = 0; k < col1; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}

// Display the result


printf("Final Array:\n");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}

You might also like