Print a Matrix

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • candexis
    New Member
    • Aug 2006
    • 51

    #1

    Print a Matrix

    Hi!!!!!!!, well i want to know how to print in screen a matrix like this:

    Matrix[4][4] = {{1,2,3,4},{5,6 ,7,8},{9,10,11, 12},{13,14,15,1 6}};

    And the output must be like this:

    1 2 3 4
    5 6 7 8
    9 10 11 12
    13 14 15 16

    Thaks for your help
  • nikhilraj
    New Member
    • Sep 2006
    • 11

    #2
    Originally posted by candexis
    Hi!!!!!!!, well i want to know how to print in screen a matrix like this:

    Matrix[4][4] = {{1,2,3,4},{5,6 ,7,8},{9,10,11, 12},{13,14,15,1 6}};

    And the output must be like this:

    1 2 3 4
    5 6 7 8
    9 10 11 12
    13 14 15 16

    Thaks for your help
    hai
    u can print the matrix by using two for loops here


    for (i=0;i<n;i++)
    {
    for(j=0;j<n;j++ )
    {
    printf("%d ",matrix[i][j]);
    }
    printf("\n");
    }
    here depends on how u declare the array

    Comment

    • dush
      New Member
      • Sep 2006
      • 27

      #3
      Hi

      Here is the more general solution:

      Code:
      #include <iostream>
      using namespace std;
      
      int main (){	
      
        int Matrix[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
      	
        for (int i=0; i<sizeof Matrix/sizeof Matrix[0]; ++i)
        {
          for (int j=0; j<sizeof Matrix[0] /sizeof Matrix[0][0]; ++j)
            printf("%03d ", Matrix[i][j]);
          cout << '\n';
        }
      return 0;
      }
      You can change type of elements in array (char, int, short ...) and number of rows and colums in matrix without editing the 'for' loop.

      Comment

      Working...