Note that there are some explanatory texts on larger screens.

plurals
  1. POcalculate the sum of diagonals in a matrix
    primarykey
    data
    text
    <p>I need to calculate the sum of two diagonals in a matrix in C++, I already have a solution for that but I must be dumb because I cant understand what it is doing, so I would like to know if there is another version which I can understand. here is the code which does the job:</p> <pre><code>cout&lt;&lt;"Jepi rangun e matrices"&lt;&lt;endl; // pra bejme manipulim me matrice katrore ku rreshtat=kolonat cin&gt;&gt;n; cout&lt;&lt;"Tani jepi elementet e matrices"&lt;&lt;endl; // lexohet matrica for(i=1;i&lt;=n;i++) { for(j=1;j&lt;=n;j++) cin&gt;&gt;a[i][j]; } d=0; s=0; // ketu e keni kushtin si dhe mbledhjen per te dy diagonalet me dy variabla te ndryshme for(i=1;i&lt;=n;i++) for(j=1;j&lt;=n;j++) { if(i==j) d=d+a[i][j]; if(j==n-i+1 || i==n-j+1) s=s+a[i][j]; } </code></pre> <p>The part that is difficult to understand is</p> <pre><code>if(j==n-i+1 || i==n-j+1) s=s+a[i][j]; </code></pre> <p>Here is the entire code that I changed but it doesnt work for the secondary diagonal:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int d=0,s=0; // ketu e keni kushtin si dhe mbledhjen per te dy diagonalet me dy variabla te ndryshme int i,j,n; int a[5][5]; cout&lt;&lt;"Jepi rangun e matrices"&lt;&lt;endl; // pra bejme manipulim me matrice katrore ku rreshtat=kolonat cin&gt;&gt;n; cout&lt;&lt;"Tani jepi elementet e matrices"&lt;&lt;endl; // lexohet matrica for(i=1;i&lt;=n;i++) { for(j=1;j&lt;=n;j++) cin&gt;&gt;a[i][j]; } for(i=1;i&lt;=n;i++) { for(j=1;j&lt;=n;j++) { if(i==j) d+=a[i][j]; //principal diagonal if(i+j==n-1) s+=a[i][j];//secondary diagonal } } cout &lt;&lt; d &lt;&lt; endl; cout &lt;&lt; s &lt;&lt; endl; cin.get(); cin.get(); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload