0

I'm working on a code that will multiply two matrices and print the result. This specific code is meant to ask the user to define the bounds of the matrices (i.e. the (M)x(N) of the matrix) then ask for each matrix by row.

The trouble I'm having is that I can make the code work if I define how big the matrices are in the code before compiling, but need to make it semi-dynamic (changing the matrix size) when the program is run.

Here is what I've got, this DOES NOT RUN correctly and I would appreciate some advice on how to fix it!

#include<stdio.h> 

int main() 
{ 
int i,j,l,e,f; 
int a[e][f],b[e][f],c[e][f]; 

printf("Enter the number of rows: ");
scanf("%d", e);
printf("\nEnter the number of columns: ");
scanf("%d", f);

printf("Enter 1st matrix: \n"); 
for (i=0;i<e;++i) 
	{ 
	printf("\nEnter #%d row: ",(i+1)); 
		for (j=0;j<f;++j) 
		scanf("%d", &a[i][j]); 
	} 

printf("\n\n"); 
printf("Enter 2nd matrix: \n"); 

for (i=0;i<e;++i) 
	{ 
	printf("\nEnter #%d row: ",(i+1)); 
		for (j=0;j<f;++j) 
		scanf("%d",&b[i][j]); 
	} 

printf("\n\n"); 

for (i=0;i<e;++i) 
	{ 
		for (j=0;j<f;++j) 
		c[i][j]=0; 
	} 

for (j=0;j<f;++j) 
	{ 
		for (i=0;i<e;++i) 
		{ 
		for (l=0;l<e;++l) 
		c[i][j] = c[i][j] + (a[i][l])*(b[l][j]); 
		} 
	} 

printf("The resultant matrix is:\n\n"); 

for (i=0;i<e;++i) 
	{ 
		for (j=0;j<f;++j) 
		printf("%4d",c[i][j]); 
		printf("\n\n"); 
	} 

return 0;
}

I don't get any error code because apparently it compiles no problem, but then the program stops responding and I have to end it.

2
Contributors
1
Reply
3
Views
6 Years
Discussion Span
Last Post by N1GHTS
0

Untested, but throwing it out there to give you an idea of the direction of where my mind is going.

// User input for number of rows
int r;
printf("Enter the number of rows: ");
scanf("%d", r);

// User input for number of columns
int c;
printf("\nEnter the number of columns: ");
scanf("%d", c);

// Create the SINGLE array
int ArraySize = x + (y * c);
int *Array = (int *)malloc(ArraySize * sizeof(int) * 2);

// User input for rows of each matrix
int i=0, j, a=0;
for (;a<2;a++) 
  for (;i<r;i++) {
    printf("\nEnter %d%s matrix, row #%d: ", (a+1), (a==0)?("st"):("nd"), (i+1));
    for (j=0;j<c;j++) 
       scanf("%d", &Array[((i*c)+j)+(a*ArraySize)]);
  }

// Multiply
for (i=0;i<ArraySize;i++)
  Array[i] *= Array[i+ArraySize];

// Display the results
// .. don't have time to code this part, but the results are in Array[(col * c) + row]

Normally I would have tested it and all that but I don't have time right now. Hope this helps you out.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.