Sum of all submatrix-Approach-2

Did not understand. Can you explain this over a google meet?

Hi Anjanpreet,
whatever is ur doubt u tell me over here only… i cant come over google meet or anything…
i suggest u to watch video lecture again and try to dry run the code urself… u will get a better insight…

I’am getting the sum as a garbage value when I’am taking size greater than 2.
#include
using namespace std;
void sumSubmatrix(int a[][10],int size)
{
int sum=0;
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
a[i][j+1]+=a[i][j];

	}
}
for(int i=0;i<size;i++)
{
	for(int j=0;j<size;j++)
	{
		a[i+1][j]+=a[i][j];
		
	}
}
for(int li=0;li<size;li++)
{
	for(int lj=0;lj<size;lj++)
	{
		for(int bi=li;bi<size;bi++)
		{
			for(int bj=lj;bj<size;bj++)
			{
				sum+=a[bi][bj]-a[li-1][bj]-a[bi][lj-1]+a[li-1][lj-1];
			}
		}
	}
}
cout<<"sum is:"<<sum<<endl;

}
int main()
{
int a[10][10];
int size;
cin>>size;
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
cin>>a[i][j];
}

}

sumSubmatrix(a,size);



return 0;

}

Hi @anjanpreetsingh1019
u have to put this condition like this
sum+=a[bi][bj]-(li-1>=0 ? a[li-1][bj] : 0)-(lj-1 >= 0 ? a[bi][lj-1] : 0)+(li-1>=0 && lj-1>=0 ? a[li-1][lj-1] : 0);
corrected code --> https://ide.codingblocks.com/s/639796

hi @anjanpreetsingh1019
i hope its clear now?? u just have to place the check so that value doesn’t go less than 0 as negative index in array will give garbage value only…

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.