Sum of all sub matrices approach 2

sir i wrote the following code but it is not giving the correct answer. please check this code.

#include
using namespace std;
int find_sum(int arr[][100], int n);
int main()
{
int n, arr[100][100];
cin>>n;
for(int row = 0; row<n; ++row)
for(int col = 0; col<n; ++col)
cin>>arr[row][col];
for(int row = 0; row<n; ++row)
for(int col = 1; col<n; ++col)
arr[row][col]+=arr[row][col-1];
for(int col = 0; col<n; ++col)
for(int row = 1; row<n; ++row)
arr[row][col]+=arr[row-1][col];
cout<<find_sum(arr, n)<<endl;
return 0;
}
int find_sum(int arr[][100], int n)
{
int sum = 0;
for(int li = 0; li<n; ++li)
for(int lj = 0; lj<n; ++lj)
for(int bi = li; bi<n; ++bi)
for(int bj = lj; bj<n; ++bj)
sum+=arr[bi][bj]-arr[li-1][bj]-arr[bi][lj-1]+arr[li-1][lj-1];
return sum;
}

Save your code on ide.codingblocks.com and then share its link.

@pratyush63 sir this is my code -

@pratyush63 sir i gave u the link please check it. what have i done wrong in it?

You are not handling the case when li=0 or lj=0… This result in Negative array indexes in line 27 which produces garbage values.
Refer this code:
https://ide.codingblocks.com/s/302272

1 Like