Skip to content
Sharp

Core Java · interview question

How can you modify a while loop to correctly calculate the total price only for items priced over $20, given the following code? int total = 0; while (index < prices.length) { total += prices[index]; index++; }?

Multiple choiceHardchapter-1-curatedpremiumcore-javaloops-and-iteration
java
while (index < prices.length) { if (prices[index] > 20) { total += prices[index]; } index++; }
Choose one answer
Answer and explanation

Correct answer

A. Add an if condition inside the loop

Why

By adding an 'if' condition inside the loop to check if 'prices[index]' is greater than 20, only those items will be added to 'total'. This filters the items based on price.

Test yourself on Core Java

A free test with instant, explained results. No account needed.

Start free test
All Core Java questions →