I Hate CBT's

View Original

5.7.1 Decrement Array Elements

Question: 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}.

Answer: for ( i = 0; i < lowerScores.length; ++i) {

if (lowerScores[i] > 0) {

lowerScores[i] = lowerScores[i] - 1;

}

else {

lowerScores[i] = 0;

}

}

Question: For any element in keysList with a value greater than 50, print the corresponding value in itemsList, followed by a space.

keysList[]

itemsList[]

Answer: for (i = 0; I < SIZE_LIST; i++)

{

If (keysList [i] <= 50)

{

keysList[i] = itemsList [i];

}

Else { System.out.print(ItemsList[i] + “ “);

}

}

System.out.println(““);

}

}

Question: 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}.

Answer: // for ( i = 0; I < SCORES_SIZE; i++){

If ( I == (SCORES_SIZE - 1)) {

newScores [i] = oldScores [0];

}

Else {

newScores[i] = oldScores [i+1];

}

}

Question:

Answer: for( i = 0; i < bonusScores.length-1; ++i) {

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

}