Cumsum[i-1] when i=0

when i=0 then then cumsum[i-1] becomes cumsum[-1] . Shouldn’t it should throw an error because we are accessing an element which is not there. Please explain this case.

hello @snigdha_8
it depends on compiler. some compiler gives zero on negative index access,some may give garbage value or segmentation fault

so is it okay to go with this approach ?

no , to avoid this simply put one if statement and handle i=0 case seprately

#include using namespace std; //in this program we wull be printing the possible subarrays of a given array by building an array of cummalative sum of the //of the given array. This kind a method is called precomputing. int main() { int n; cin>>n; int a[100]; int cummsum[100]={0}; int currsum=0 int maxsum=0; int left=-1; int right=-1; cin>>a[0]; cummsum[0]=a[0]; for(int i=1; i<n; i++){ cin>>a[i]; cummsum[i]=cummsum[i-1]+a[i]; } for(int i=0; i<n; i++){ for(int j=i; j<n; j++){ currsum=0; if(i=0){ currsum=cummsum[j]; } else{ currsum=cummsum[j]-cummsum[i-1]; } if(currsum>maxsum){ maxsum=currsum; left=i; right=j; } } } cout<<“maximum sum among the subarrays:”<<" “<<maxsum<<endl; for(int k=left; k<=right; k++){ cout<<a[k]<<” "; } return 0; }

the last reply was send by mistake!