ProgrammingHardCAT · MBA placement

Prices by day: 1, 5, 3, 8, 6, 10. Profit is earned in every rise: whenever tomorrow's price is higher than today's, buy today and sell tomorrow. The procedure sums all such daily rises. What is printed?

Prices by day: 1, 5, 3, 8, 6, 10. Profit is earned in every rise: whenever tomorrow's price is higher than today's, buy today and sell tomorrow. The procedure sums all such daily rises. What is printed?
total = 0
for i = 0 to n - 2
    if p[i+1] > p[i] then total = total + p[i+1] - p[i]
end for
Print total
  1. A. 13
  2. B. 9
  3. C. 4
  4. D. 3

Correct answer: A. 13

The rises are 4, 5 and 4 for a total of 13. The overall range of 9 ignores the intermediate falls, summing the falls gives 4 instead, and counting rises gives 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic