c++ nothing beyond arrays Write a loop that sets each array element to the sum o
ID: 3576494 • Letter: C
Question
c++ nothing beyond arrays
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:
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.
#include <iostream>
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;
}
Explanation / Answer
#include <iostream>
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 */
int tmp = bonusScores[SCORES_SIZE-1],hat;
for(i=SCORES_SIZE-2;i>=0;i--)
{
hat = bonusScores[i];
bonusScores[i] += tmp;
tmp = hat;
}
for (i = 0; i < SCORES_SIZE; ++i) {
cout << bonusScores[i] << " ";
}
cout << endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.