Is this implementation to the video correct? and what about garbage value if i=0 and j=0,also show correct output for 2 1 1 1 1

#include<iostream>
using namespace std;
int main()
{  
  int n;
  cin>>n;
  int a[100][100]={0};
  int presum[100][100];
  for(int i=0;i<n;i++)
  {
  	for(int j=0;j<n;j++)
  	{
  		cin>>a[i][j];
  		if(j==0)
  		{presum[i][j]=a[i][j];}
  		else{
  		presum[i][j]=presum[i][j-1]+a[i][j];}
  	}
  }
  for(int i=1;i<n;i++)
  {
  	for(int j=0;j<n;j++)
  	{
  		presum[j][i]+=presum[j-1][i];
  		}
  }
  
  int sum=0;
  for(int i=0;i<n;i++)
{ for (int j=0;j<n;j++)
{
	for(int k=i;k<n;k++)
	{
		for (int l=j;l<n;l++)
		{
			sum+=presum[k][l]-presum[i-1][l]-presum[k][j-1]+presum[i-1][j-1];
			
		}
		}
	
}}
cout<<sum;
 return 0;
}

Hello @sagar_aggarwal,

The junk values are getting added and subtracted from the sum for the cases:

When li=0
when lj=0
You have to check for these cases before computing the sum.
Modified Code:

Hope, this would help.
Give a like if you are satisfied.

#IS THIS CORRECT NOW?

#include<iostream>
using namespace std;
int main()
{  
  int n;
  cin>>n;
  int a[100][100]={0};
  int presum[100][100];
  for(int i=0;i<n;i++)
  {
  	for(int j=0;j<n;j++)
  	{
  		cin>>a[i][j];
  		if(j==0)
  		{presum[i][j]=a[i][j];}
  		else{
  		presum[i][j]=presum[i][j-1]+a[i][j];}
  	}
  }
  for(int i=0;i<n;i++)
  {
  	for(int j=0;j<n;j++)
  	{   if(j!=0){
  		presum[j][i]+=presum[j-1][i];}
  		}
  }
  for(int i=0;i<n;i++)
  {
  	for(int j=0;j<n;j++)
  	{
  		cout<<presum[i][j]<<" ";
  		}
  		cout<<endl;
  }
  
  int sum=0;
  for(int i=0;i<n;i++)
{ for (int j=0;j<n;j++)
{
	for(int k=i;k<n;k++)
	{
		for (int l=j;l<n;l++)
		{
			sum+=presum[k][l];
			if(i-1>=0){
			sum-=presum[i-1][l];}
			if(j-1>=0){
			sum-=presum[k][j-1];}
			if(i-1>=0&&j-1>=0)
			{
			sum+=presum[i-1][j-1];}
			
		}
		}
	
}}
cout<<sum;
 return 0;
}

also brother we have used a nested loop for implementing presum matrix is time complexity still n^4 or n^2+ n^4??

Hello @sagar_aggarwal,

  1. Yes, it seems correct.

  2. The complexity is O(n^4) we will consider the higher power of n.

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.