Topic-Problem Solving on 2d arrays :video no-2

what is wrong in this code? why it not generating sum as 16 when my input is
2 2
1 1
1 1

code:-
#include
using namespace std;

int main()
{
#ifndef ONLINE_JUDGE
freopen(“input.txt”, “r”, stdin);
freopen(“output.txt”, “w”, stdout);
#endif

int m, n;
cin >> m >> n;

int arr[m][n];

for (int i = 0; i < m; i++)
{
	for (int j = 0; j < n; j++)
	{
		cin >> arr[i][j];
	}
}


for (int i = 1; i < m; i++)
{
	for (int j = 0; j < n; j++)
	{
		arr[i][j] = arr[i][j] + arr[i - 1][j];
	}
}

for (int i = 0; i < m; i++)
{
	for (int j = 1; j < n; j++)
	{
		arr[i][j] = arr[i][j] + arr[i][j - 1];
	}
}

int sum = 0;

//for top left
for (int l_i = 0; l_i < m; l_i++)
{
	for (int l_j = 0; l_j < n; l_j++)
	{
		//For bottom right
		for (int r_i = l_i; r_i < m; r_i++)
		{
			for (int r_j = l_j; r_j < n; r_j++)
			{

				sum += ((arr[r_i][r_j]) - (arr[l_i - 1][r_j]) - (arr[r_i][l_j - 1]) + (arr[l_i - 1][l_j - 1]));
			}
		}
	}
}

cout << sum << endl;



return 0;

}

If the above code is wrong, plz provide me the correct code

this line is incorrect
because if l_i is 0 then it will cause problem

correct way

sum += arr[r_i][r_j];
if (l_i > 0)
	sum -= (arr[l_i - 1][r_j]);
if (l_j > 0)
	sum -= (arr[r_i][l_j - 1]);
if (l_i > 0 && l_j > 0)
	sum += (arr[l_i - 1][l_j - 1]);
}

i hope you understood it
if yes then plz let me know

#include
using namespace std;

int main()
{
#ifndef ONLINE_JUDGE
freopen(“input.txt”, “r”, stdin);
freopen(“output.txt”, “w”, stdout);
#endif

int m, n;
cin >> m >> n;

int arr[m][n];

for (int i = 0; i < m; i++)
{
	for (int j = 0; j < n; j++)
	{
		cin >> arr[i][j];
	}
}


for (int i = 1; i < m; i++)
{
	for (int j = 0; j < n; j++)
	{
		arr[i][j] = arr[i][j] + arr[i - 1][j];
	}
}

for (int i = 0; i < m; i++)
{
	for (int j = 1; j < n; j++)
	{
		arr[i][j] = arr[i][j] + arr[i][j - 1];
	}
}

int sum = 0;

//for top left
for (int l_i = 0; l_i < m; l_i++)
{
	for (int l_j = 0; l_j < n; l_j++)
	{
		//For bottom right
		for (int r_i = l_i; r_i < m; r_i++)
		{
			for (int r_j = l_j; r_j < n; r_j++)
			{

				sum += (arr[r_i][r_j]);
				if (l_i > 0)
				{
					sum -= (arr[l_i - 1][r_j]);
				}
				if (l_j > 0)
				{
					sum -= (arr[r_i][l_j - 1]);
				}
				if (l_j > 0 && r_j > 0)
				{
					sum += (arr[l_i - 1][l_j - 1]);
				}
			}
		}
	}
}

cout << sum << endl;



return 0;

}

I have corrected this . but for the input
2
1 1
1 1
sum should come as 16 but it is coming as 14.can you tell me where am i doing wrong?

Modified Code

1 Like

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.