Control Flow Statements: break
Not Started

In Apex, the keyword and statement break enables developers to take control over a loop's flow.

The break statement can terminate a loop's iteration sequence immediately. For instance, the following for loop would be pointless:

for(Integer num : numbers){ break; // nothing below would ever run }

Typically, we use the break statement conditionally. Suppose you have to sum up every integer in a list until you encounter an index containing the element 0. If it does, the loop should exit immediately. Otherwise all elements should be summed:

Integer[] numbersToSum = new Integer[] {5, 10, 2, 0, 3, 6}; Integer sumOfIntegers = calculateSum(numbersToSum); // sumOfIntegers will be 17 public Integer calculateSum(Integer[] numbers){ Integer sum = 0; for(Integer i = 0; i < numbers.size(); i++){ if(numbers[i] == 0){ break; } sum += numbers[i]; } return sum; }

In this example, the loop will iterate through the list, and if the current index contains a 0, the loop will terminate immediately, and the next line that will be executed is return sum;. If the list does not contain a 0 element, all the indexes will be accessed, and their values summed.

Challenge

The getTotalWithDiscounts() method in the PricingCalculator should subtract each element of the discountList parameter from the total parameter and return the updated total.

For example, given the parameters (10, 10, 10) and 50. The output of the method should be 20. Because 50 - 10 - 10 - 10 gives a total of 20.

If the parameters are (1, 2, 3) and 7. The output of the method should be 1. Because 7 - 1 - 2 - 3 gives a total of 1.

However, there is one exception to this rule: the total should never be negative. If, at any point, the discount being iterated over is greater than the total, the loop should break, and the method should return the total with the discounts that have already been applied.

If the parameters are(5, 10) and 7 the output should be 2 not -8. This is because 7 - 5 - 10 gives us a new total -8 but we need to break before the total becomes negative.

7 - 5 is 2, so the total is set to 2. But since the next element in the list, 10, is greater than our total, 2, we should break out of the loop instead of continuing to compute the total.

Pseudocode has been provided to help with the solution.