Section 4. Chapter 2
single
Challenge: for Loop
Swipe to show menu
Task
Swipe to start coding
You are shopping and want to calculate the total cost of buying multiple items at the same price. To do this, implement the method CalculateTotalCost(int itemPrice, int quantity) that uses a for loop to add itemPrice to a running total, once for each item in quantity.
- Initialize
totalCostto0. - The loop starts at
i = 0and runs whilei < quantity— this ensuresitemPriceis added exactlyquantitytimes. - Add
itemPricetototalCoston each iteration. - Return
totalCostat the end of the method.
Solution
Everything was clear?
Thanks for your feedback!
Section 4. Chapter 2
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat