193k views
2 votes
Write a loop that subtracts 1 from each element in lowerScores. If the element was already 0 or negative, assign 0 to the element. Ex: lowerScores = {5, 0, 2, -3} becomes {4, 0, 1, 0}.Sample program:#include using namespace std;int main() { const int SCORES_SIZE = 4; vector lowerScores(SCORES_SIZE); int i = 0; lowerScores.at(0) = 5; lowerScores.at(1) = 0; lowerScores.at(2) = 2; lowerScores.at(3) = -3; for (i = 0; i < SCORES_SIZE; ++i) { cout << lowerScores.at(i) << " "; } cout << endl; return 0;}Below, do not type an entire program. Only type the portion indicated by the above instructions (and if a sample program is shown above, only type the portion.)

User Deqing
by
4.5k points

1 Answer

1 vote

Answer:

Replace <STUDENT CODE> with

for (i = 0; i < SCORES_SIZE; ++i) {

if(lowerScores.at(i)<=0){

lowerScores.at(i) = 0;

}

else{

lowerScores.at(i) = lowerScores.at(i) - 1;

}

}

Step-by-step explanation:

To do this, we simply iterate through the vector.

For each item in the vector, we run a check if it is less than 1 (i.e. 0 or negative).

If yes, the vector item is set to 0

If otherwise, 1 is subtracted from that vector item

This line iterates through the vector

for (i = 0; i < SCORES_SIZE; ++i) {

This checks if vector item is less than 1

if(lowerScores.at(i)<1){

If yes, the vector item is set to 0

lowerScores.at(i) = 0;

}

else{

If otherwise, 1 is subtracted from the vector item

lowerScores.at(i) = lowerScores.at(i) - 1;

}

}

Also, include the following at the beginning of the program:

#include <vector>

User Carles Fenoy
by
4.5k points