Write a C program that does the following matrix operation: . For example, given
ID: 3653436 • Letter: W
Question
Write a C program that does the following matrix operation: . For example, given 2*2 matrix A and matrix B, is defined as follows:
In the main function do the following:
Declare 3 4*4 2-D integer arrays (A, B, and Result)
Get the dimension of the 2 matrices from the user (same size for both A and B, they are all square matrices)
Get the values of the 2 matrices from the user, 1 row at a time
Call function printMatrix to print matrix A
Call function printMatrix to print matrix B
Call function matrixMultiplicationto compute AxB, the result is put in matrixResult
Call function printMatrix to print matrix Result
Function prototypes are given as follows:
Void printMatrix (int [][4], int dimension);
Void matrixMultiplication(int result[][4], int a[][4], int b[][4], int dimension);
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void printMatrix(int A[][4],int size);
void matrixMultiplication(int result[][4], int a[][4], int b[][4], int dimension);
int main(){
int size;
printf("please enter the size of array ");
scanf("%d",&size);
int A[size][size],B[size][size],result[size][size];
int i,j;
printf("enter the values of first matrix ");
for ( i = 0 ; i < size; i++)
for( j = 0 ; j < size ;j++)
scanf("%d",&A[i][j]);
printf("enter the values of second matrix ");
for ( i = 0 ; i < size; i++)
for( j = 0 ; j < size ;j++)
scanf("%d",&B[i][j]);
printf("printing A ");
printMatrix(A,size);
printf("printing B ");
printMatrix(B,size);
matrixMultiplication(result,A,B,size);
printf("printing result ");
printMatrix(result,size);
}
//printMatrix function
void printMatrix(int A[][4],int size){
// declare i and j
int i,j;
// loop for size times ( iterate over rows
for ( i = 0 ; i < size; i++){
// loop for size times ( iterate over columns
for( j = 0 ; j < size ;j++)
// print A[i][j]
printf("%4d ",A[i][j]);
printf(" ");
}
}
// matrix Multiplication
void matrixMultiplication(int result[][4], int a[][4], int b[][4], int size){
// declare i ,j and k
int i,j,k;
printf("Multiplication of the Matrices: ");
//loop for size times ( iterate over rows
for(i=0;i<size;i++)
{
//loop for size times ( iterate over columns
for(j=0;j<size;j++)
{
result[i][j]=0;
for(k=0;k<size;k++)
// multiply the two components
result[i][j] += a[i][k] * b[k][j];
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.