88.0k views
3 votes
Functions with vector parameters C++

Define a function IsSumNegative() that takes one integer vector parameter and one integer parameter. The function computes the sum of the vector's elements that are greater than or equal to the integer parameter. Then, the function returns true if the sum is negative, and returns false otherwise.
Ex: If the input is:
4
-1 1 -5 -7
-1
then the vector has 4 elements {-1, 1, -5, -7}, and the integer parameter is -1. The output is:
False, the sum of the elements that are greater than or equal to -1 is not negative.
Note: The sum is zero if no element is greater than or equal to the integer parameter.
--------------------------
#include
#include
using namespace std;

/* Your code goes here */

int main() {
vector inVector;
int size;
int input;
int i;
int x;
bool result;

// Read the vector's size, and then the vector's elements
cin >> size;
for (i = 0; i < size; ++i) {
cin >> input;
inVector.push_back(input);
}

cin >> x;

result = IsSumNegative(inVector, x);

if (result) {
cout << "True, the sum of the elements that are greater than or equal to " << x << " is negative." << endl;
}
else {
cout << "False, the sum of the elements that are greater than or equal to " << x << " is not negative." << endl;
}

return 0;
}

User Tom West
by
7.7k points

1 Answer

4 votes

Answer:

Here's the pseudocode for the IsSumNegative function:

function IsSumNegative(vector, integer)

sum = 0

for each element in vector

if element >= integer

sum = sum + element

end for

if sum < 0

return true

else

return false

end if

end function

Step-by-step explanation:

Note: This code assumes that the vector parameter is a std::vector<int> type.

User Lucas Smith
by
7.9k points