title: Sum of the elements of diagonal of matrix c++
body: <p>I want to find the sum of the diagonals of matrix that defined by user with this code , it works for main diagonal but not for secondary diagonal and i don't understand what the problem is. Any help would be appreciated.</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  int main() {
      int r, c, j,i,k,sum1,sum2;
      cout &lt;&lt; "Enter the size of matrix: ";
      cin &gt;&gt; j;
      int matrix[j][j];
  
      for (r = 0; r &lt; j; r++) {
          for (c = 0; c &lt; j; c++) {
              cout &lt;&lt; "matrix" &lt;&lt; "[" &lt;&lt; r &lt;&lt; "]" &lt;&lt; "[" &lt;&lt; c &lt;&lt; "] = ";
              cin &gt;&gt; matrix[r][c];
          }
      }
      cout &lt;&lt; "\n";
  
      for ( i = 0; i &lt; j; i++) {
          for ( k = 0; k &lt; j; k++) {
              cout &lt;&lt; " "&lt;&lt;matrix[i][k] &lt;&lt; " ";
          }
          cout &lt;&lt; "\n";
      }
  
  cout&lt;&lt;"\n";
  
  cout&lt;&lt;"Main diagonal is: ";
  for( i=0;i&lt;j;i++){
      cout&lt;&lt;matrix[i][i];
  }
  cout&lt;&lt;"\n";
  
  
  for( i=0;i&lt;j;i++){
      sum1=sum1+matrix[i][i];}
      cout&lt;&lt;"Sum of the elements of main diagonal is: "&lt;&lt;sum1;
      cout&lt;&lt;"\n";
      cout&lt;&lt;"\n";
  
  cout&lt;&lt;"Secondary diagonal is: ";
  for(i=0,k=j-1;i&lt;j;i++,k--){
      cout&lt;&lt;matrix[i][k];
  }
  
  
  for(i=0,k=j-1;i&lt;j;i++,k--){
      sum2=sum2+matrix[i][k];
      }
  
      cout&lt;&lt;"Sum of the elements of secondary diagonal is: "&lt;&lt;sum2;
      return 0;
  }
  
  </code></pre>