Search code examples
c++arrayssum

How do I calculate the sum of all the array numbers after the first negative?


Can you help me with this problem? All I could do was count all the negative numbers. Here is my code:

using namespace std;
int main()

{
    const int SIZE = 10;
    int arr[SIZE]{};
    int number=0;
    srand(time(NULL));
    cout << "Your array is: " << endl;
    for (int i=0; i<SIZE; i++)
    {
        int newValue = rand()%20-10;
        arr[i] = newValue;
        cout << arr[i] << " ";
        if (arr[i] < 0)
        {
            for (int j=-1; j<SIZE; j++)
            {
                number = arr[i];
                sum += fabs(number);
                break;
            }
        }
    }
    cout << endl;
    cout << "Sum of elements after first element < 0 is: " << sum;
    cout << endl;
}

Solution

  • One way is to have a flag that is zero to start with that is switched on after the first negative:

    int flag = 0;
    int sum = 0;
    for (std::size_t i = 0; i < SIZE; ++i){
        sum += flag * arr[i];
        flag |= arr[i] < 0;
    }
    

    This approach carries the advantage that you don't need an array at all: substituting the next number from standard input for arr[i] is sufficient.