in output after using this approch is garbage because you have used (li-1) and (lj-1) while finding sum but li starts from 0
Sum of all submatrix (approach 2)
Only the pseudocode was given in the video.
When you actually code it, you can impose extra conditions that if (li-1)< 0 or (lj-1)<0 then set that value to 0…
where should i put this condition inside loop.plz help
for(li=0;li<3;li++)
{
for(lj=0;lj<3;lj++)
{
for(bi=li;bi<3;bi++)
{
for(bj=lj;bj<3;bj++)
{
sum+=a[bi][bj]-a[li-1][bj]-a[bi][lj-1]+a[li-1][lj-1];
}
}
}
}
Before this step sum+=a[bi][bj]-a[li-1][bj]-a[bi][lj-1]+a[li-1][lj-1];
Check the value of li-1 and lj-1
If li-1 is <0 no need to add this part -a[li-1][bj]+a[li-1][lj-1];
If lj-1 is <0 no deed to add this part -a[bi][lj-1]+a[li-1][lj-1];
I have made changes shown below still getting garbage value . Can you plz write that part of code (after loop 4). plz help.
for(li=0;li<3;li++)
{
for(lj=0;lj<3;lj++)
{
for(bi=li;bi<3;bi++)
{
for(bj=lj;bj<3;bj++)
{
if(li-1<0)
sum+=a[bi][bj]-a[bi][lj-1];
if(lj-1<0)
sum+=a[bi][bj]-a[li-1][bj];
else
sum+=a[bi][bj]-a[li-1][bj]-a[bi][lj-1]+a[li-1][lj-1];
}
}
}
}
The conditional statement should be in this order:
if((lj-1<0)&&(li-1<0)) //Do not forget to check this condition
{
}
else if (li-1<0)
{
}
else if(lj-1<0)
{
}
else
{
}
Thanks for helping me constantly. i am sending you the whole with changes recommended by you but it was still giving the garbage value.My code is correct till prefix sum array as it was showing the correct array int the output.
#include
using namespace std;
int main()
{
int a[3][3];
int i,j,li,lj,bi,bj,sum=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
cin>>a[i][j];
}
for(i=0;i<3;i++)
{
for(j=1;j<3;j++)
{
a[i][j]=a[i][j]+a[i][j-1];
}
}
for(j=0;j<3;j++)
{
for(i=1;i<3;i++)
{
a[i][j]=a[i][j]+a[i-1][j];
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
’
for(li=0;li<3;li++)
{
for(lj=0;lj<3;lj++)
{
for(bi=li;bi<3;bi++)
{
for(bj=lj;bj<3;bj++)
{
if(li-1<0&&lj-1<0)
{
sum=sum+a[bi][bj];
}
else if(li-1<0)
{
sum=sum+a[bi][bj]-a[bi][lj-1];
}
else if(lj-1<0)
{
sum=sum+a[bi][bj]-a[li-1][bj];
}
else
{
sum=sum+a[bi][bj]-a[li-1][bj]-a[bi][lj-1]+a[li-1][lj-1];
}
}
}
}
}
cout<<sum;
return 0;
}
Please save your code on ide.codingblocks.com and then share its link. I will make the necessary changes.
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.