title: Transpose of a sparse matrix in C++
body: <p>I am very new to C++. Here, I am trying to find out transpose of a sparse matrix. Here is the code:</p>
  
  <pre><code>#include&lt;iostream&gt;
  using namespace std;
  class transposeM{
      int m1[20][20],m2[20][20],i,j,row,column,t;
  public:
      void read(){
          t=0;
          cout&lt;&lt;"Enter the number of row: \n";
          cin&gt;&gt;row;
          cout&lt;&lt;"enter the number of column: \n";
          cin&gt;&gt;column;
  
          for(i=0;i&lt;row;i++){
              for(j=0;j&lt;column;j++){
                  cin&gt;&gt;m1[i][j];
  
                  if(m1[i][j]){
                      t++;
  //                  cout&lt;&lt;"first t is:"&lt;&lt;t;
                  //if non zero
                              m2[t][0]=i+1;
                              m2[t][1]=j+1;
                              m2[t][2]=m1[i][j];
  
                  }
  
  
              }
          }
  
          m2[0][0]=row;
          m2[0][1]=column;
          m2[0][2]=t;
      }
  
      void displaysp(){
  cout&lt;&lt;"sparse matrix is: \n";
          for(i=0;i&lt;=t;i++){
              for(j=0;j&lt;3;j++){
                  cout&lt;&lt;m2[i][j]&lt;&lt;" ";
              }
              cout&lt;&lt;"\n";
          }
      }
  
      void transpose(){
          int transpose[20][3];
  
                          transpose[0][0]=m2[0][0];
                          transpose[0][1]=m2[0][1];
                          transpose[0][2]=m2[0][2];
          cout&lt;&lt;"Transpose is: \n";
          int q=1;
          for(i=1;i&lt;=column;i++){
              for(int p=1;p&lt;=t;p++){
                  if(m2[p][1]==i){
                      transpose[q][0]=m2[p][0];
                      transpose[q][1]=m2[p][1];
                      transpose[q][2]=m2[p][2];
                      q++;
  
                  }
              }
          }
  
          for(i=0;i&lt;=column;i++){
              for(j=0;j&lt;3;j++){
                  cout&lt;&lt;transpose[i][j]&lt;&lt;" ";
              }
              cout&lt;&lt;"\n";
          }
  
      }
      void display(){
          for(i=0;i&lt;row;i++){
                  for(j=0;j&lt;column;j++){
                      cout&lt;&lt;m1[i][j]&lt;&lt;" ";
  
  
                  }
                  cout&lt;&lt;"\n";
              }
  
      }
  };
  int main(int argc,char ** argv){
      transposeM obj;
      obj.read();
      obj.display();
      obj.displaysp();
      obj.transpose();
      return 0;
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>Enter the number of row: 
  2
  enter the number of column: 
  2
  0
  1
  2
  0
  0 1 
  2 0 
  sparse matrix is: 
  2 2 2 
  1 2 1 
  2 1 2 
  Transpose is: 
  2 2 2 
  2 1 2 
  1 2 1 
  </code></pre>
  
  <p>But something went wrong; read matrix and convert the same to sparse matrix is fine. But finding out transpose got some logical error.</p>