uzmeed
uzmeed

Reputation: 21

cannot print the matrix on the console

Using the following code I cannot print any of the matrix A, B or C.
As a testing purpose even not an int is printed.

#include"stdio.h"
int main()
{
#define row 3
#define col 3
    int A[row][col]={ {1,2,3},{2,3,4},{3,4,5}};
    int B[row][col]={ {1,0,0},{0,1,0},{0,0,1}};
    int i,j;
    int C[row][col]={ {0,0,0},{0,0,0},{0,0,0}};
    int temp=2;

    for (i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            C[i][j]=A[i][j]*B[j][i]+C[i][j];
        }
    printf("%d   \n ", C[i][j]);
        getchar();
    }


}

Upvotes: 1

Views: 123

Answers (3)

Jabberwocky
Jabberwocky

Reputation: 50775

The problem in your code is here:

for (i=0;i<3;i++)
{
    for(j=0;j<3;j++)
    {
        C[i][j]=A[i][j]*B[j][i]+C[i][j];
    }
    // j contains 3 here therefore you acess the C array out of bounds
    printf("%d   \n ", C[i][j]); //<<<<<<<<<<<<<<
    getchar();
}

You probably want this:

  ...

  // Multiplication of A and B
  for (i = 0; i<3; i++)
  {
    for (j = 0; j<3; j++)
    {
      C[i][j] = A[i][j] * B[j][i] + C[i][j];
    }
  }

  // Display C    
  for (i = 0; i<3; i++)
  {
    for (j = 0; j<3; j++)
    {
      printf ("%d ", C[i][j]);
    }

    printf("\n");
  }

  getchar();
  ...

Even better: write a Display3x3Matrix and use it:

void Display3x3Matrix(int m[3][3])
{
  for (int i = 0; i<3; i++)
  {
    for (int j = 0; j<3; j++)
    {
      printf("%d ", m[i][j]);
    }    
    printf("\n");
  }
}

...

printf("A\n");
Display3x3Matrix(A);
printf("\nB\n");
Display3x3Matrix(B);
printf("\nC\n");
Display3x3Matrix(C);

Upvotes: 3

Dineth Cooray
Dineth Cooray

Reputation: 192

Change the for loop as follows

for (i=0;i<3;i++)
{
    for(j=0;j<3;j++)
    {
        C[i][j]=A[i][j]*B[j][i]+C[i][j];
        printf("%d", C[i][j]);
    }
     printf("\n");
}

Demo

Upvotes: 0

Gaterde
Gaterde

Reputation: 819

This works for me (printing the "A" Matrix):

    #define row 3
    #define col 3

    int A[row][col] = { { 1,2,3 },{ 2,3,4 },{ 3,4,5 } };

    int rows, columns;
    for (rows = 0; rows<3; rows++)
    {
        for (int columns = 0; columns<3; columns++)
        {
            printf("%d     ", A[rows][columns]);
        }
        printf("\n");

    }

Upvotes: 1

Related Questions