Max sum subarrayy

int cumulativeSum(int n,int a[]){
int s[n] = {};
s[0] = a[0];
for (int i=1;i<n;i++){
s[i] += s[i-1] + a[i];
}
int sum = INT_MIN;
for (int i=0;i<n;i++){
for (int j=i;j<n;j++){
if (sum < s[j] - s[i-1])
sum = s[j] - s[i-1];
}
}
return sum;
}
In the above piece of code, In the nested loop if have written if (sum < s[j] - s[i - 1]) why this line is not giving runtime error as i ranges from 0 to n and at some instance i - 1 = -1, it results to out of bounds of array.

Send your complete code by saving on ide

An array is contiguous memory location which stores values of same type.

The name of an array A very quickly devolves to a pointer to the 0th element of A
int A[3]={1,2,3};
cout<<A;
//it will give the address of memory location assigned to 0th element of A i.e. A is know to be a pointer to the 0th element of the array.
cout<<*A;
//it will print 1

The syntax A[i] is equivalent to *(A + i)
so, A[-1] is *(address of A[0]-1)
Thus, the junk value store at this address is displayed

You are just excessing parts of the stack that are not used, you could continue till you reach the end of the allocated space for the stack and it’d crash eventually.

The language simply says what should happen if you access the elements within the bounds of an array. It is left undefined what happens if you go out of bounds. It might seem to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it’ll still work the next time you run the program.

hope, this would help. If you still have doubts, feel free to ask.

here’s the link

s[i] is equivalent to *(s+i)
where,
s points to the address of memory location assigned to s[0].

Now, for i=-1,
s[-1] is equivalent to *(s-1)
which means, the content of the memory location prior to address pointed by s (or address of s[0]). That value is a junk value.
C++ does not support this error.