200k views
4 votes
C++ Proagram

Write a loop that sets each array element to the sum of itself and the
next element, except for the last element which stays the same.
Be careful not to index beyond the last element. Ex:
Initial scores: 10, 20, 30, 40
Scores after the loop: 30, 50, 70, 40
The first element is 30 or 10 + 20, the second element is 50
or 20 + 30, and the third element is 70 or 30 + 40. The last element
remains the same.
Follow this code
#include
using namespace std;
int main() {
const int SCORES_SIZE = 4;
int bonusScores[SCORES_SIZE];
int i = 0;
bonusScores[0] = 10;
bonusScores[1] = 20;
bonusScores[2] = 30;
bonusScores[3] = 40;
/* Your solution goes here */
for (i = 0; i < SCORES_SIZE; ++i) {
cout << bonusScores[i] << " ";
}
cout << endl;
return 0;
}

User Csymvoul
by
3.9k points

1 Answer

2 votes

Answer:

Replace /* Your solution goes here */

with

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

bonusScores[i] += bonusScores[i+1];

}

Step-by-step explanation:

In C++, the index of an array starts from 0 and ends at 1 less than the size of the array;

Using the analysis in the question, the above code (in the answer section) iterates from the index element (element at 0) to the second to the last element (element at size - 2)';

This is to ensure that the element of the array only adds itself and the next element;except for the last index which remains unchanged

The following operation is done in each iteration.

When i = 0,

bonusScores[0] = bonusScores[0] + bonusScores[0+1];

bonusScores[0] = bonusScores[0] + bonusScores[1];

bonusScores[0] = 10 + 20

bonusScores[0] = 30

When i = 1,

bonusScores[1] = bonusScores[1] + bonusScores[1+1];

bonusScores[1] = bonusScores[1] + bonusScores[2];

bonusScores[1] = 20 + 30

bonusScores[1] = 50

When i = 2,

bonusScores[2] = bonusScores[2] + bonusScores[2+1];

bonusScores[2] = bonusScores[2] + bonusScores[3];

bonusScores[2] = 30 + 40

bonusScores[2] = 70

This is where the iteration stops

User Ionn
by
4.2k points