Error in output

This is my code of sub_maximum 2

#include
#include
using namespace std;

int main()
{
int a[8]={-4,1,3,-2,6,2-8,-9,4},sumarr[8]={0};
int left=-1,right=-1,max_sum=INT_MIN,sum;

sumarr[0]=a[0];

for(int i=1;i<=8;i++)
{

    sumarr[i]=sumarr[i-1]+a[i];

}

for(int i=0;i<=8;i++)
{
    for( int j=i;j<=8;j++)
    {
        sum=0;
        sum=sumarr[j]-sumarr[i-1];


   if(max_sum<sum)
    {
        max_sum=sum;
        left=i;
        right=j;
    }
    }
}
cout<<"Max Sum  = "<<max_sum<<endl;
for(int i=left;i<=right;i++)
{
    cout<<a[i];
}

}

hello @tddewan2
image

here u cannot access i-1 when i is 0 . becuase i-1 will be -1 in that case.

so handle it by adding an if statement.
if i==0 then sum=sumarr[j]

I’m getting your point but i just copy the logic from the video and its working in the video but not on my Machin

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

int main() { int a[8]={-4,1,3,-2,6,2-8,-9,4},sumarr[8]={0}; int left=-1,right=-1,max_sum=INT_MIN,sum; sumarr[0]=a[0]; for(int i=1;i<=8;i++) { sumarr[i]=sumarr[i-1]+a[i]; } for(int i=0;i<9;i++) { cout<<sumarr[i]; }

pls share ur code using cb ide.