C++ – Find numbers between first and last negative numbers in Array

One possible solution:

#include <iostream>
using namespace std;

int main() {
  float a[] = { 1.5, 55, 5, 4.4,7.1,9,8,2,4.2, -3, -3.2, 5.2, -9 };
  float sumofnums = 0;

  int size = sizeof(a) / sizeof(a[0]);  // size is 13 here, this allows you
                                        // to determine the size automatically
  int first = 0;
  int last = size - 1;

  for (int g = 0; g < size; g++) {
    if (a[g] < 0) {
      first = g;
      break;
    }     
  }

  for (int g = size - 1; g >= 0; g++) {
    if (a[g] < 0) {
      last = g;
      break;
    }
  }

  for (int g = first; g <= last; g++) {
    sumofnums += a[g];
  }

  cout << "Sum is " << sumofnums << endl;
}

It should be clear enough without comments.

Leave a Comment