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;
}
CodePudding user response:
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.
CodePudding user response:
In your specific case, there are numerous simple and efficient solutions, like that offered by Bathsheba.
However, for a more general case of summing elements in an array after the first value satisfying a given condition, you can use the std::find_if
and std::accumulate
functions from the STL, providing appropriate lambda functions to do the test (checking for negative) and summation (the sum = fabs(number)
in your code implies that you want to sum the absolute values of the remaining elements1).
Here's a possible implementation:
#include <cstdlib> // std::abs, std::rand
#include <ctime> // std::time
#include <algorithm> // std::find_if
#include <numeric> // std::accumulate
#include <iostream>
using std::cout, std::endl;
int main()
{
const int SIZE = 10;
int arr[SIZE]{};
// Generate random array...
std::srand(static_cast<unsigned int>(time(nullptr)));
cout << "Your array is: " << endl;
for (int i = 0; i < SIZE; i ) {
int newValue = std::rand() % 20 - 10;
arr[i] = newValue;
cout << arr[i] << " ";
}
// Sum all abs values after first negative ...
auto is_neg = [](int i) { return i < 0; };
auto fn = std::find_if(std::begin(arr), std::end(arr), is_neg);
auto sum_abs = [](int a, int b) { return a std::abs(b); };
// Set the sum to ZERO if the first negative is the last element...
int sum = (fn == std::end(arr)) ? 0 : std::accumulate( fn, std::end(arr), 0, sum_abs);
cout << endl;
cout << "Sum of elements after first element < 0 is: " << sum;
cout << endl;
return 0;
}
1 If this is not the case, and you just want the sum of the actual values, then you can omit the 4th (sum_abs
) argument in the call to std::accumulate
(and the definition of that lambda).