Cumulative Sum(2d Array)

/// Reference :: https://docs.google.com/presentation/d/1zWPIZf-m9uK6WtNd-H9tGl5WFEo1yIWM8FxrujX5bSo/edit#slide=id.p4

#include<bits/stdc++.h>
using namespace std;
int main()
{
int n, m, a, b, c, d;

cout << "Enter Row and Column :: ";
cin >> n >> m;

int v[n][m], s[n][m];

cout << "\nEnter Array Element :: " << "\n";
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
cin >> v[i][j];
}

for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(i == 0 && j == 0)
s[i][j] = v[i][j];
else if(i == 0 && j != 0)
s[i][j] = s[i][j-1] + v[i][j];
else if(i != 0 && j == 0)
s[i][j] = s[i-1][j] + v[i][j];
else
s[i][j] = s[i-1][j] - s[i-1][j-1] + s[i][j-1] + v[i][j];
}
}

cout << "\nEnter top left point :: ";
cin >> a >> b;

cout << "\nEnter bottom right point :: ";
cin >> c >> d;

int result = 0;

if(a == 0 && b == 0)
result = s[c][d];
else if(a == 0 && b != 0)
result = s[c][d] - s[c][b-1];
else if(a != 0 && b == 0)
result = s[c][d] - s[a-1][d];
else if(a == c && b == d)
result = v[a][b];
else
result = s[c][d] - s[a-1][d] - s[c][b-1] + s[a-1][b-1];

cout << "\nSummation of Rectangle is :: " << result << "\n";

return 0;
}

Comments