+ 2

why this is not giving the correct sum of a given matrix?

this is the code. #include <iostream> using namespace std; int main() { int arr[5][5] = { {1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15}, {16,17,18,19,20}, {21,22,23,24,25} }; int csum=0; for(int i=0;i<5;i++) { for(int j=0;j<5;j++) { csum += arr[i][j]; } } int checksum=0; for(int i=1;i<=20;i++) checksum += i; cout << "it should be : " << checksum << endl; cout << "it is : " << csum << endl; }

25th Mar 2018, 11:11 AM
shobhit
shobhit - avatar
3 Respuestas
+ 2
Sum of first 25 numbers = 25*13. The second loop calculates sum from 1 to 20, as opposed to the matrix which calculates from 1 to 25. Thats why (checksum!=csum) is true.
25th Mar 2018, 11:33 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
that was a silly mistake. Anyways thnx for your help as always.
25th Mar 2018, 1:40 PM
shobhit
shobhit - avatar
+ 1
Glad that I could help...
25th Mar 2018, 4:25 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar