The task is to find the sum of the elements located between the first and second negative elements, but for some reason, a large negative number is displayed instead of an answer.

int i, k, s = 0, a[10]; for(int i = 0; i<n; i++) if(a[i] < 0) { k = i; break; } { for(i = k + 1;i<n;i++) s += a[i]; } 
  • 3
    the question is - how are you initialized n and the array itself? - Yuriy Orlov
  • @ user204021, a not initialized, its elements refer to random addresses, because of this, the values ​​themselves are unpredictable. What with n is not at all clear. - Bars
  • Do you have one task for the whole group? The second identical question for the day and absolutely the same problems. ru.stackoverflow.com/questions/497989/… - Flowneee

1 answer 1

Try this code (you forgot the stop condition on the 2nd negative element):

 #include <iostream> using namespace std; int main() { int n = 10; int k, s = 0, a[n] = {1, 2, -3, 4, 5, 6, -7, 8, 9, 10}; for(int i = 0; i < n; i++) { if(a[i] < 0) { k = i; break; } } for(int i = k + 1; i < n; i++) { if (a[i] < 0) { break; } s += a[i]; } cout << s; return 0; } 
  • I work through Builder 6 and use the StringGrid component, so I could not write an array, as in your code. All other changes did not help, the number has now become positive, but still as large. - user204021
  • one
    @ user204021 Have you tried to see what you have in the array before counting something? Maybe you did not fill it with anything and there is just garbage? - Flowneee
  • @ user204021 my program works correctly, it's up to you. Try to test here , for example, and realize that everything is working correctly. - Denis